简体   繁体   中英

Deserializing JSON object with unknown fields

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM