Hamza
Hamza

Reputation: 1583

Parse Dynamic JSON string

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

Upvotes: 1

Views: 466

Answers (2)

Amadeus Sanchez
Amadeus Sanchez

Reputation: 2585

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

Upvotes: 0

spender
spender

Reputation: 120548

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;
}

Upvotes: 3

Related Questions