Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize a json string where name property is a number

Tags:

json

c#

json.net

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"

like image 836
shresthaal Avatar asked Feb 03 '26 19:02

shresthaal


1 Answers

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

like image 134
Rao Ehsan Avatar answered Feb 05 '26 09:02

Rao Ehsan