简体   繁体   中英

Handle dynamic structure of Json

I have Json structure like this :

metadata : {
   id : "something",
   data : {
      1 : {
         id : "something",
         simple : {
             ASD3472GJVMKG : { id : "something", name : "something" },
             A892SADKLAWEN : { .. },
             KVMSD309234KG : { .. },
      2 : { .. }, 
      ...

There are two attributes which generated dynamically , they are attributes of data and attributes of simple . The name attributes of data are kind of number which generated incrementaly. The name attributes of simple are random string which generated dynamically.

Actually, I have done deserializing the attributes of simple with kind of process that not simple (foreach and substring everywhere). BTW, I am using Json.NET and C#. What kind of solution I need to do with this bad Json structure? I have seen JObject and Dictionary class but still don't get it to figure that.

Thanks in advance

The structure you have shown above is not valid JSON. You'll need to either produce valid JSON for input to JSON.NET, or create a special parser especially for this type of data.

If you are working with valid JSON and simply don't know the property names in advance, you can use one of the following deserialization methods.

  1. Deserialize the object to a JObject instead of a more specific type. This allows you to access the individual properties of the object.
  2. Deserialize the object to a Dictionary<string, JObject> . In practice this is nearly equivalent to the previous option.
  3. Deserialize the object to an object that contains the following field. During deserialization, all properties which do not map to some other field or property in the object model will be added to this dictionary.

     [JsonExtensionData] private Dictionary<string, JObject> _extensionData; 

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