简体   繁体   中英

JSON.NET unknown type deserialization

Assume I have following json strings, where some property name differes ("dataA", "dataB"), but it contains the same structure

{
  "mainprop": "val",
  "dataA": { "prop1":"val", "prop2":"val"}
}

and

{
  "mainprop": "val",
  "dataB": { "prop1":"val", "prop2":"val"}
}

How I can deserialize these jsons to objects with following generic class

Class Generic
{
  string mainprop;
  DataClass data; 
}

Class DataClass
{
  string prop1;
  string prop2;
}

In another words, how I can handle deserialization based on name of the property.

You can always do a generic deserialization (to Dictionary<string, object> ) and then map the values yourself, but I suspect this isn't what you're looking for.

The only way I can think off the top of my head is to make two dummy objects for deserialization / serialization purposes only.

public class GenericA : Generic {
    public DataClass dataA { get { return data; } set { data = value; } }
}

public class GenericB : Generic {
    public DataClass dataB { get { return data; } set { data = value; } }
}

Generic a = JsonConvert.DeserializeObject<GenericA>("JSON using dataA");
Generic b = JsonConvert.DeserializeObject<GenericB>("JSON using dataB");

I haven't tested this code.

Edit

You may want to attribute your data property with [JsonIgnore] so you can serialize GenericA and GenericB without having the same property twice.

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