Reputation: 362620
When serializing an object using the System.Runtime.Serialization.Json.DataContractJsonSerializer
, is there a way to set the "root" or top-level key in the JSON string?
For example, here is a class:
[DataContract]
public class Person
{
public Person() { }
public Person(string firstname, string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
}
When it is serialized using...
public static string Serialize<T>(T obj)
{
Json.DataContractJsonSerializer serializer =
new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.Default.GetString(ms.ToArray());
ms.Dispose();
return retVal;
}
The produced JSON string looks like:
{"FirstName":"Jane","LastName":"McDoe"}
Is there a way to have the serializer prepend some value?
For example:
{Person: {"FirstName":"Jane","LastName":"McDoe"}}
Of course I could simply change my Serialize
method to wrap the returned JSON string, e.g.:
string retVal = "{Person:" + Encoding.Default.GetString(ms.ToArray()) + "}";
But I was wondering if there was some way to tell the serializer to add it? The namespace
property on the DataContract
attribute didn't seem to help.
Upvotes: 4
Views: 8279
Reputation: 87258
You can do that, but it's not something too pretty - you need to know some of the JSON to XML mapping rules which the DataContractJsonSerializer
uses. For the simple case, where you just want to wrap the object in the type name, it's fairly simple - the code below does that. You need to create the serializer with the "root" name you want (in this case I used the type name), and pass to it a XmlDictionaryWriter
instance which has been given the root element.
public class StackOverflow_7930629
{
[DataContract]
public class Person
{
public Person() { }
public Person(string firstname, string lastname)
{
this.FirstName = firstname;
this.LastName = lastname;
}
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
}
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(typeof(T), typeof(T).Name);
MemoryStream ms = new MemoryStream();
XmlDictionaryWriter w = JsonReaderWriterFactory.CreateJsonWriter(ms);
w.WriteStartElement("root");
w.WriteAttributeString("type", "object");
serializer.WriteObject(w, obj);
w.WriteEndElement();
w.Flush();
string retVal = Encoding.Default.GetString(ms.ToArray());
ms.Dispose();
return retVal;
}
public static void Test()
{
Console.WriteLine(Serialize(new Person("Jane", "McDoe")));
}
}
As was mentioned in one of the comments, working with JSON and the DataContractJsonSerializer
isn't something too friendly. Some JSON-specific libraries such as JSON.NET or the JsonValue types (nuget package JsonValue) can make your life a lot easier.
Upvotes: 1