我的问题的一些背景知识:我希望在Json.net中反序列化一些可怕的json。这个json对象是由ArcGIS服务器创建的,它发送一个'results‘对象,其格式如下:
{ "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" } } ] }现在问题出在attributes对象上:
{ "OBJECTID" : "61", "Ward" : "MyWard", "Polling Station" : "Childrens Resources Centre", "Polling District" : "E", "Constituency" : "South", "Shape" : "Polygon" }...which在某些标识符中有空格;它是由“pretty”字段别名生成的,而不是数据表名。我可以使用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,所以我可能犯过一些学生错误。欢迎任何建议!
发布于 2011-07-20 23:03:00
在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");https://stackoverflow.com/questions/6763314
复制相似问题