简体   繁体   中英

Deserialize Dynamic JSON Object

I am using a thirdparty API and the Json response that I receive back is as below. Usually, using something like

Newtonsoft.Json.JsonConvert.DeserializeObject<MyModel>(response);

I can easily create a.Net model. However, I am struggling on how to formulate the below. I've tried KeyValuePairs, strings, modifying the actual Json but cannot seem to get any joy.

What am I missing?

{
  "1": [
    {
      "qty": 1,
      "discount": "flat",
      "price": 71.68
    }
  ],
  "2": [
    {
      "qty": 1,
      "discount": "flat",
      "price": 62.75
    }
  ],
  "3": [
    {
      "qty": 1,
      "discount": "flat",
      "price": 77.28
    }
  ],
  "4": [
    {
      "qty": 1,
      "discount": "flat",
      "price": 82.88
    }
  ],
  "5": [
    {
      "qty": 1,
      "discount": "flat",
      "price": 67.84
    }
  ]
}

Now, what is throwing me is that the numbers(1,2,3,4,5) are Identifiers so will not stay constant and could change each time you receive the response.

I think Newtonsoft can do this for you.

string json = @"{
  'Email': 'james@example.com',
  'Active': true,
  'CreatedDate': '2013-01-20T00:00:00Z',
  'Roles': [
    'User',
    'Admin'
  ]
}";

var jsonReturn = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>( json );
Console.WriteLine( jsonReturn.Email );

Based on this link:https://www.newtonsoft.com/json/help/html/DeserializeObject.htm

This is the most basic explanation. Use a foreach to iterate over de nodes

Using @Liam's suggestion of JObject I have come up with this working solution

public class MyObject
{
        public int id { get; set; }
        public int qty { get; set; }
        public string discount { get; set; }
        public decimal price { get; set; }
}

and then after retrieving the JSON response...

        var jsonObj = JsonConvert.DeserializeObject<JObject>(response);

        List<MyObject> myObjects = new List<MyObject>();

        foreach (var item in jsonObj.AsJEnumerable())
        {
                var csp = JsonConvert.DeserializeObject<List<MyObject>>(item.First.ToString());

                csp.ForEach(a => { a.product_id = Convert.ToInt32(item.Path); });
                    
                myObjects.AddRange(csp);
         }

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