1

The question is similar to Deserializing JSON with unknown fields but I would like to use the built in DataContractJsonSerializer instead.

So I have JSON data like that:

{
"known1": "foo",
"known2": "bar",
"more":{ "unknown12345": { "text": "foo", "label": "bar"},
         "unknown67890": { "text": "foo","label":"bar"}
       }
}

I thought I can do the datacontract like that:

 [DataMember(Name = "known1")]
        public string K1 { get;  set;  }
 [DataMember(Name = "known2")]
        public string K2 { get;  set;  }
 [DataMember(Name = "more")]
        public Dictionary<string,TwoStringMembersClass> More {   get; set;  }

And the TwoStringMembersClass is just this:

 [DataContract(Name = "TwoStringMembersClass ")]
    public class TwoStringMembersClass 
    {
        [DataMember(Name = "text")]
        public string Text { get;  set; }

        [DataMember(Name = "label")]
        public string Label {  get;  set; }
    }

But what seems to work in JSON.Net doesn't seem to work that easy with the native JSON parser. In ReadObject() I get an ArgumentException, probably because of the Dictionary.

Any idea what's the best solution how to make this work ?

Thanks in advance.

dbc
  • 104,963
  • 20
  • 228
  • 340
Marco
  • 2,190
  • 15
  • 22
  • Can you post the definition of TwoStringMembersClass. You may also want to see if it works with Dictionary. – calum Nov 09 '11 at 12:10
  • @calum TwoStringMembersClass is now provided....also Dictionary throws the same exception :-( – Marco Nov 09 '11 at 12:32

1 Answers1

1

The DataContractJsonSerializer does not support deserializing Dictionary<TKey, TValue> from an object notation in JSON. It only supports treating a dictionary as an array. Hence the JSON needed to deserialize into the types you have defined should look like this:-

{
    "known1": "foo",
    "known2": "bar",
    "more":[{ "Key": "unknown12345", "Value": { "text": "foo", "label": "bar"} },
            { "Key": "unknown67890", "Value": { "text": "foo","label":"bar"} }
           ]
}

If the schema of the incoming JSON can't be altered then you are not going to be able to use the DataContractJsonSerializer.

AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
  • I feared as much. Thanks anyway. There is also the possibility to built the parser on your own with support of the built in xml/json parser, but it's much more affort. See details in this blog entry: http://mutelight.org/articles/using-the-little-known-built-in-net-json-parser – Marco Nov 10 '11 at 09:12
  • @sav: If I were to try to do the serialization with my one code I would use the Silverlight specific `System.Json` namespace along with LINQ extension methods. That can be quite effective and surprisingly short. – AnthonyWJones Nov 10 '11 at 09:17