Reputation: 1445
This must be trivial but I can't seem to get it done. Given the following data contract class:
public class SampleItem
{
public int Id { get; set; }
public string StringValue { get; set; }
}
when deserialized to JSON by my WCF service, provides the following output:
[{"Id":1,"StringValue":"Hello"}]
Is there any way to include the class name too? i.e.:
"SampleItem": [{"Id":1,"StringValue":"Hello"}]
Upvotes: 3
Views: 1189
Reputation: 4816
You could 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);
}
Upvotes: 3