JSON.NET JObject-如何从此嵌套的JSON结构中获取价值 [英] JSON.NET JObject - how do I get value from this nested JSON structure
问题描述
我有这个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"
}
}
我将其解析为JSON.NET JObject,并且可以使用例如(string)RequestBody.SelectToken("client_id")
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")
如何使用JPath表达式(或通过访问JSON.NET JObject的子对象)访问"user_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")
,我无法执行此操作来解析JSON的数据"部分:
and I can't do this to parse the 'data' part of the JSON:
JObject RequestBodyData = JObject.Parse((string)RequestBody.SelectToken("data"));
编译器似乎将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')
并且我不想将原始JSON解析为自定义C#对象,因为我正在开发一个解决方案,该解决方案需要能够将JSON通用地解析为JObject(或用于处理JSON的任何其他类型的通用对象) ,因此可以相对一致的方式进行解析.
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.
推荐答案
SelectToken("data[0].user_id")
不起作用,因为JSON中没有数组.您应该改用SelectToken("data.user_id")
.
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.
提琴: https://dotnetfiddle.net/K0X4ht
这篇关于JSON.NET JObject-如何从此嵌套的JSON结构中获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!