Include class name in WCF Json Serialization

This should be trivial, but I can't do it. Given the following contract data class:

public class SampleItem
{
    public int Id { get; set; }
    public string StringValue { get; set; }
}

when deserializing in JSON by my service, WCF provides the following output:

[{"Id":1,"StringValue":"Hello"}]

Is there a way to include the class name? i.e:.

"SampleItem": [{"Id":1,"StringValue":"Hello"}]
+3
source share
1 answer

You can try something like this:

private dynamic AddClassName(SampleItem item)
{
      return new {SampleItem = item};
}

and

var item = new SampleItem {Id = 1, StringValue = "Hello"};
dynamic itemClassName = AppendClassName(item);
string json = new JavaScriptSerializer().Serialize(itemClassName);
Debug.WriteLine(json);

Edit - this works for all types:

private static string GetJsonWrapper<T>(T item)
{
    string typeName = typeof(T).Name;
    string jsonOriginal = new JavaScriptSerializer().Serialize(item);
    return string.Format("{{\"{0}\":{1}}}", typeName, jsonOriginal);
}
+3
source

All Articles