我认为NewtonSoft的JsonTextReader
可以给你想要的,使用Path
,LineNumber
和LinePosition
属性。
此代码,例如:
var s = @"
{
""obj"": {
""foo"": ""bar""
},
""arr"": [
1,
2,
3
]
}
";
using(var sr = new System.IO.StringReader(s))
{
var r = new Newtonsoft.Json.JsonTextReader(sr);
while (r.Read())
Console.WriteLine(r.LineNumber + ":" + r.LinePosition + " : " + r.Path);
}
会给下面的输出:
2:5 :
3:14 : obj
3:16 : obj
4:18 : obj.foo
4:24 : obj.foo
5:9 : obj
6:14 : arr
6:16 : arr
7:13 : arr[0]
8:13 : arr[1]
9:13 : arr[2]
10:9 : arr
11:5 :
但是,如果你真的想只用字符的索引工作,你可能要替换所有换行符和carriage在你的json字符串中返回到空格,所以一切都在一行...
现在要获取字符串中特定位置的路径很简单:
var charIndex = 48;
var s = @"
{
""obj"": {
""foo"": ""bar""
},
""arr"": [
1,
2,
3
]
}
";
s = s.Replace("\n", " ").Replace("\r", " ");
var path = "";
using(var sr = new System.IO.StringReader(s))
{
var r = new Newtonsoft.Json.JsonTextReader(sr);
while (r.Read() && r.LinePosition <= charIndex)
path = r.Path;
}
Console.WriteLine(path); // obj.foo
这不正是你想要的,但'JToken'明确实现['IJsonLineInfo'(https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_IJsonLineInfo.htm)接口。如果[解析](https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JToken_Parse_1.htm),则使用['new JsonLoadSettings {LineInfoHandling = LineInfoHandling.Load}'](https:// www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_Linq_JsonLoadSettings_LineInfoHandling.htm),那么每个标记都会记住它的行号和字符串中的位置。 – dbc
而且,给定一个'JToken',你可以通过['token.Path'](https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_Linq_JToken_Path.htm)获得它的路径。 – dbc