Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - JSON.NET JObject - how do I get value from this nested JSON structure

I have this JSON:

{
    "client_id": "26075235",
    "client_version": "1.0.0",
    "event": "app.uninstall",
    "timestamp": 1478741247,
    "data": {
        "user_id": "62581379",
        "site_id": "837771289247593785",
        "platform_app_id": "26075235"
    }
}

I parse it into a JSON.NET JObject and I can successfully access the first level of values using e.g. (string)RequestBody.SelectToken("client_id")

How do I access the value of "user_id" using a JPath expression (or by accessing a child object of the JSON.NET JObject)? This doesn't work:

(string)RequestBody.SelectToken("data[0].user_id")

and I can't do this to parse the 'data' part of the JSON:

JObject RequestBodyData = JObject.Parse((string)RequestBody.SelectToken("data"));

as the compiler seems to recognise RequestBody.SelectToken("data") as an object (I get the error 'Can not parse object into string')

and I don't want to parse the original JSON into a custom C# object as I'm developing a solution that needs to be able to generically parse JSON into a JObject (or any other type of generic object for handling JSON), so it can be parsed in a relatively consistent way.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

SelectToken("data[0].user_id") doesn't work because there isn't an array in your JSON. You should use SelectToken("data.user_id") instead.

Fiddle: https://dotnetfiddle.net/K0X4ht


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...