Ale*_*lex 7 .net json json.net
我正在使用NewtonSoft Json.NET库来解析.NET应用程序中的JSON文件.我需要做的是传递节点的名称,并获取节点(如果存在),无论其事先未知的级别如何.
例如在一个文件中:
string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""ATest"": {
""MyTest"":
[
""blah"",
""blah""
]
}
}";
Run Code Online (Sandbox Code Playgroud)
有没有办法只使用该值"MyTest"来获取该节点而不必知道父类的名称jObject["ATest"]["MyTest"][0]?
car*_*ira 17
AFAIK有没有为类似XPath的查询语法JToken/ JObject,但你可以做一个相当容易-看看下面的代码.
public static class StackOverflow_13033174
{
public static void Test()
{
string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""ATest"": {
""MyTest"":
[
""blah"",
""blah""
]
}
}";
JObject jo = JObject.Parse(json);
JToken myTest = jo.Descendants()
.Where(t => t.Type == JTokenType.Property && ((JProperty)t).Name == "MyTest")
.Select(p => ((JProperty)p).Value)
.FirstOrDefault();
Console.WriteLine(myTest);
}
}
Run Code Online (Sandbox Code Playgroud)
这是使用JSONPath 的另一种方法:
请参阅: https: //dotnetfiddle.net/EIKjnH
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
public static class StackOverflow_13033174
{
public static void Main()
{
string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""ATest"": {
""MyTest"":
[
""blah"",
""blah""
]
}
}";
JObject jo = JObject.Parse(json);
JToken myTest = jo.SelectToken("*.MyTest");
Console.WriteLine(myTest);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3960 次 |
| 最近记录: |