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

1
  • Use JObject instead? Commented Nov 11, 2015 at 22:04

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Don't even need to read the individual elements, you can deserialize to dynamic from JSON.net stackoverflow.com/questions/4535840/…
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.