2

我的问题的一些背景:我希望在 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,所以我可能犯了一些小学生错误。欢迎任何建议!

4

1 回答 1

2

阅读有效的JPath.ParseMain代码JPath.cs

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");
于 2011-07-20T15:02:59.690 回答