我的问题的一些背景:我想在 Json.net 中反序列化一些可怕的 json。此 json 对象由 ArcGIS Server 创建,并发送格式如下的“结果”对象:
{ "results" : [ { "layerId" : 10, "layerName" : "Polling Districts", "value" : "MyWard", "displayFieldName" : "Ward", "attributes" : { "OBJECTID" : "61", "Ward" : "MyWard", "Polling Station" : "Childrens Resources Centre", "Polling District" : "E", "Constituency" : "South", "Shape" : "Polygon" } } ] }
现在的问题是属性对象:
{ "OBJECTID" : "61", "Ward" : "MyWard", "Polling Station" : "Childrens Resources Centre", "Polling District" : "E", "Constituency" : "South", "Shape" : "Polygon" }
...在某些标识符中有空格;它是由“漂亮”字段别名而不是数据表名称生成的。我可以使用 linq selectToken 获取所有其他字段,但我正在寻找“投票站”。
我已经尝试了很多查询变体:
string pollingStation = (string)jObj.SelectToken("results[0].attributes[Polling Station]"); // Unexpected character while parsing path indexer: P
string pollingStation = (string)jObj.SelectToken("results[0].attributes[\"Polling Station\"]"); //Unexpected character while parsing path indexer: "
string pollingStation = (string)jObj.SelectToken("results[0].attributes.\"Polling Station\""); // No error, pollingStation is null
string pollingStation = (string)jObj.SelectToken("results[0].attributes.Constituency"); // No error, pollingStation is South (correct)
我用谷歌搜索、搜索了 json.net 帮助并阅读了此处已发布的许多问题 - 这些问题似乎都没有解决这个特定问题。也许我只是太笨了。您可能还会看出我不精通 c# 或 Linq,这是我第一次使用 Json.net,所以我可能犯了一些小学生错误。欢迎提出任何建议!
最佳答案
阅读 JPath.cs
中的 JPath.ParseMain
代码是有效的
var json = @"{ ""results"" : [ { ""layerId"" : 10, ""layerName"" : ""Polling Districts"", ""value"" : ""MyWard"", ""displayFieldName"" : ""Ward"", ""attributes"" : { ""OBJECTID"" : ""61"", ""Ward"" : ""MyWard"", ""Polling Station"" : ""Childrens Resources Centre"", ""Polling District"" : ""E"", ""Constituency"" : ""South"", ""Shape"" : ""Polygon"" } } ] }";
var jObj = JObject.Parse(json);
var pollingStation = (string)jObj.SelectToken("results[0].attributes.['Polling Station']");
备注:在 2013 年之前的 JSon.Net 中,它无需任何形式的转义即可工作:
var pollingStation = (string)jObj.SelectToken("results[0].attributes.Polling Station");
关于c# - 使用 Json.net C# 反序列化 json - 标识符中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6763314/