Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 815
scully Avatar asked Apr 06 '26 17:04

scully


1 Answers

I think Newtonsoft can do this for you.

string json = @"{
  'Email': '[email protected]',
  '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

like image 69
John Goes Avatar answered Apr 09 '26 05:04

John Goes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!