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

淺唱寂寞╮ 提交于 2019-12-20 12:31:24

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/40538001/json-net-jobject-how-do-i-get-value-from-this-nested-json-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!