How to get the depth attribute value of the jobobject object & do not judge whether the key exists or not & get the key value with special characters


Foreword: sometimes we often use the jobject object to receive data, and quickly get the value of the specified key through the jobject. The order is OK. But if you encounter the following jobobject object object, how can you quickly get the data?

  "details": {
    "threeds2.fingerprint": "123"
  "paymentData": "456"


Normally, if you want to get the value of the key: threeds2. Fingerprint, how do you get it?

As follows:

JObject jobj=Newtonsoft.Json.JsonConvert.DeserializeObject(str);

string finger=jobj["details"]["threeds2.fingerprint"];

But there are risks in writing like this. First, we do not add any key judgment, and it is easy to report an exception. So, we can write it in another way

Newtonsoft.Json.Linq.JObject jobj = Newtonsoft.Json.JsonConvert.DeserializeObject(str);

                if (jobj.ContainsKey("details"))
                    Newtonsoft.Json.Linq.JToken jtoken = jobj["details"];
                    if (jtoken.Value("threeds2.challengeResult")!=null)
                        string finger = jtoken["threeds2.challengeResult"].ToString();

In order to avoid reporting exceptions, various judgments are added, which is not very good,The best solution is as follows:


  Key points: Here we need to note: the selecttoken method supports us to enter the access path of the depth key to obtain the data, and the parent-child level uses “.” connection. If the key contains special symbol points, it is wrapped in brackets and single quotation marks. Moreover, this method does not throw an exception. If the path is wrong or does not exist, the return value is null.