1

I am getting a JSON response from a server but the JSON is not in a one format. So obviously there is no point of creating classes to deserialize it. So, I tried to use dynamic but I am unable to read the response.

The sample JSON String is

" {"hm_xytrict":"HM Tricky District - oop","hmSD":"HM Pool District"}"

Note that "hm_xytrict" and "hmSD" will be different every time

I am using

dynamic jsonResponse = JsonConvert.DeserializeObject(responseString);

For this specific case I can use jsonResponse.hm_xytrict and jsonResponse.hmSD but since they are also dynamic so how can I read jsonResponse for all cases.

Thank you, Hamza

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Hamza
  • 1,593
  • 2
  • 19
  • 31

2 Answers2

3

So you can use a different part of the JSON.NET api to parse and extract data from your object:

var jObj = JObject.Parse(json);
foreach (JProperty element in jObj.Children())
{
    string propName = element.Name;
    var propVal = (string)element.Value;
}
spender
  • 117,338
  • 33
  • 229
  • 351
  • 1
    Don't even need to read the individual elements, you can deserialize to dynamic from JSON.net http://stackoverflow.com/questions/4535840/deserialize-json-object-into-dynamic-object-using-json-net – Brian Rudolph Nov 11 '15 at 22:29
0

Even more interesting, you can directly parse a JSON string to a dynamic object

string responseString = @"{""hm_xytrict"":""HM Tricky District - oop"",""hmSD"":""HM Pool District""}";

dynamic jsonResponse = JObject.Parse(responseString);
foreach (var item in jsonResponse)
{
    Console.WriteLine(item.Name);
    Console.WriteLine(item.Value);
}

Which in your example will output

hm_xytrict
HM Tricky District - oop
hmSD 
HM Pool District
Amadeus Sanchez
  • 2,375
  • 2
  • 25
  • 31