8

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.

Yuck
  • 49,664
  • 13
  • 105
  • 135
Almo
  • 15,538
  • 13
  • 67
  • 95
  • json can only serialize plain objects. can't you use some other form of serialization that allows typing? – Einacio Aug 24 '11 at 13:27
  • [Dynamic?](http://msdn.microsoft.com/en-us/library/dd264736.aspx) @einacio, they specifically asked to "not have to send extra information about what type the object is", which, say, xsd would be. – bzlm Aug 24 '11 at 13:27
  • so @Almo want magic typing on a static typed language. could send the type as an extra data in the json, but i don't know if c++ can create objets using strings instead of classname php-style – Einacio Aug 24 '11 at 13:39
  • I was wondering why the serializer doesn't include any type info in its output. I found a place where the .net serializer will, but it seems to be non-standard and won't work with serializers outside .net. And I'm not in C++. – Almo Aug 24 '11 at 14:48

2 Answers2

3

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

Community
  • 1
  • 1
Roy Goode
  • 2,940
  • 20
  • 22
  • Thanks, I'll look at that once we upgrade to VS2010. – Almo Aug 24 '11 at 13:40
  • I think if you're not using VS2010, you'll need to create your own serializer/deserializer using collections, such as Dictionary objects to represent the JSON field names and values. – Roy Goode Aug 24 '11 at 13:45
0

Additional info:

http://www.codeproject.com/KB/IP/fastJSON.aspx

When this library encodes JSON, it gives enough info for completely automatic reparsing.

This doesn't suit my purpose that well though, since it includes a bunch of C#-specific info, and we're working cross-language here.

Almo
  • 15,538
  • 13
  • 67
  • 95