Question

I have a web service that returns the following json

{
   "1": 1.654764367578323,
   "3": 1.654764367578323,
   "4": 1.654764367578323,
   "6": 1.654764367578323,
   "12": 1.13901127184207
}

In addition there might be 10 or 15 or 24 like below. So I need to check if the following names are in the json string 1,3,4,6,10,15,24

{
   "1": 1.654764367578323,
   "3": 1.654764367578323,
   "4": 1.654764367578323,
   "6": 1.654764367578323,
   "10": 1.13901127184207
}

I want to deserialize the above json so I tried

dynamic d = JsonConvert.DeserializeObject(jsonstring);

but I cannot do d.1 and get the value 1.654764367578323.

However, in the watch I get "End of expression expected"

Was it helpful?

Solution

You can cast the object returned by JsonConvert.DeserializeObject(jsonstring) to JObject and from there you can read values just like this.

JObject d = (JObject)JsonConvert.DeserializeObject(jsonString);
string value1 = d["1"].Value<string>();

Here is Demo

You can always check whether returned JToken is null, it will be null if JObject is not able to find the property provided in indexer.

bool attributeExist = d[attribute] != null;

See Here

OTHER TIPS

Try d[12] instead. It depends alot on your Json libary though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top