Sunday, 1 January 2017

Decode JSON Object in C# without prior knowledge of type




I have some working code:




String objstr = "{\"m_children\":[{\"m_children\":null,\"m_name\":\"child0\"},{\"m_children\":null,\"m_name\":\"child1\"}],\"m_name\":\"Root\"}";
byte[] byteArr = Encoding.ASCII.GetBytes(objstr);
MemoryStream ms = new MemoryStream(byteArr);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Node));

Node obj = (Node)ser.ReadObject(ms);


What bugs me is that I have to know the type of the object contained in the string before I decode it. I wanted to send an object encoded in JSON over a TCP pipe, and not have to send extra information about what type the object is.


Answer




With .NET 4.0 you can use dynamic objects. Why not try out this solution from another question: Deserialize JSON into C# dynamic object?


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...