使用Json.net C#反序列化json - 标识符中的空格

时间:2011-07-20 14:10:39

标签: c# json json.net arcgis-server

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

1 个答案:

答案 0 :(得分:2)

阅读JPath.ParseMainJPath.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");
相关问题