Deserialize nested JSON into C# objects

后端 未结 3 1756
野的像风
野的像风 2020-11-27 06:55

I am getting JSON back from an API that looks like this:

{
  \"Items\": {
    \"Item322A\": [{
      \"prop1\": \"string\",
      \"prop2\": \"string\",
             


        
相关标签:
3条回答
  • 2020-11-27 07:06

    You could use Json.Parse so that you can query into the data -- and just use the single model.

    private class Info
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
        public int Prop3 { get; set; }
        public bool Prop4 { get; set; }
    }
    
    var result = JObject.Parse(resultContent);   //parses entire stream into JObject, from which you can use to query the bits you need.
    var items = result["Items"].Children().ToList();   //Get the sections you need and save as enumerable (will be in the form of JTokens)
    
    List<Info> infoList = new List<Info>();  //init new list to store the objects.
    
    //iterate through the list and match to an object. If Property names don't match -- you could also map the properties individually. Also useful if you need to dig out nested properties.
    foreach(var subItem in items){
    foreach(JToken result in subItem){
    Info info = result.ToObject<Info>();
    infoList.add(info);
    }}
    
    0 讨论(0)
  • 2020-11-27 07:09

    Use this this site for representation:

    https://quicktype.io/csharp/

    something like this may help you

    public class Item322A
    {
        public string prop1 { get; set; }
        public string prop2 { get; set; }
        public int prop3 { get; set; }
        public bool prop4 { get; set; }
    }
    
    public class Item2B
    {
        public string prop1 { get; set; }
        public string prop2 { get; set; }
        public int prop3 { get; set; }
        public bool prop4 { get; set; }
    }
    
    public class Items
    {
        public List<Item322A> Item322A { get; set; }
        public List<Item2B> Item2B { get; set; }
    }
    
    public class jsonObject
    {
        public Items Items { get; set; }
        public List<string> Errors { get; set; }
    }
    

    Here is how to deserialize (use JsonConvert class):

    jsonObject ourlisting = JsonConvert.DeserializeObject<jsonObject>(strJSON);
    
    0 讨论(0)
  • 2020-11-27 07:24

    For "Items" use a Dictionary<string, List<Info>>, i.e.:

    class Response
    {
        public Dictionary<string, List<Info>> Items { get; set; }
        public string[] Errors { get; set; }
    }
    
    class Info
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
        public int Prop3 { get; set; }
        public bool Prop4 { get; set; }
    }
    

    This assumes that the item names "Item322A" and "Item2B" will vary from response to response, and reads these names in as the dictionary keys.

    Sample fiddle.

    0 讨论(0)
提交回复
热议问题