简体   繁体   中英

Deserialize a json string where name property is a number

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"

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM