-3

i have a json in below format

  {{
      "encoding_version": 1,
      "root": {
        "_type": "dictionary",  
        "test1": 0,
        "test2": 6593,
        "test3": ".key.test",
        "test4": "key.test",
        "test5": ".key.14",     
        "test6": 6159
      }
    }}

i am trying to get "test5" value which is 14

var data = (JObject)JsonConvert.DeserializeObject(inputJson);
var id = data["test5"];
            
            

however getting it null,Please help.

Harsh
  • 23
  • 5
  • Or https://www.newtonsoft.com/json/help/html/QueryJsonSelectToken.htm – Rand Random May 25 '21 at 11:13
  • https://dotnetfiddle.net/4ayaru – Rand Random May 25 '21 at 11:21
  • 2
    Could you please provide a **valid** json? You can use [this website](https://jsonformatter.curiousconcept.com/) to check validity. – Peter Csala May 25 '21 at 11:27
  • You can use `data.SelectToken("root.test5")` as shown in [JSON.NET JObject - how do I get value from this nested JSON structure](https://stackoverflow.com/q/40538001/3744182). Or use the null-conditional `?[]`: `data["data"]?["test5"]` as shown in [Json.NET get nested jToken value](https://stackoverflow.com/q/42290485/3744182). Then to get a string value you can cast the return to a `string` as shown in [How to get a string value from a JToken](https://stackoverflow.com/q/33754692/3744182). – dbc May 25 '21 at 20:09

1 Answers1

0

You have provide JSON with two times curl braces, i have made this small correction in your input JSON :

{
  "encoding_version": 1,
  "root": {
  "_type": "dictionary",
  "test1": 0,
  "test2": 6593,
  "test3": ".key.test",
  "test4": "key.test",
  "test5": ".key.14",
  "test6": 6159
  }
}

As your deserialization is correct and you are looking for value of "test5" which is ".key.14". Your desired key is two level down in JSON i.e. first go for "root" and then "test5". Hence your code will look like:

string test5Value = (string)result["root"]["test5"]; 

output => .key.14

If you want 14 then you might need to split output string and take out the required value.