Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

c# - Find Subelement in JObject of unknown property name

I have the following Json-Structure converted to JObject:

{
  "success": false,  
  "errors": {
    "13": {    
      "errorCode": "address missing"
     },
    "4711": {
      "year":1395
    }
  }
}

I want to retrieve the value of "errorCode". The problem is that the child under "errors" can be ANY number so I cannot simply use

jsonDetail.SelectToken("errors.13.errorCode")

to retrieve the value under "errorCode".

There always is only ONE child that contains "errorCode" but there can be additional children too (which I want to ignore)-

question from:https://stackoverflow.com/questions/65886405/find-subelement-in-jobject-of-unknown-property-name

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can search the JObject using SelectToken and a JSONPath expression https://www.newtonsoft.com/json/help/html/SelectToken.htm

In your case you just need this

var errorCode = jsonDetail.SelectToken("$..errorCode");

You can find more detail on JSONPath expressions here https://goessner.net/articles/JsonPath/ (this link was found in Newtonsoft's own documentation)

From the documentation on JSONPath you can see that $ is for the root object, and the .. is the recursive descent, so this will recursively search the root object for a child with the token name of errorCode


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...