首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用标识符内的Json.net C#空格反序列化json

问使用标识符内的Json.net C#空格反序列化json
EN

Stack Overflow用户
提问于 2011-07-20 22:10:39
回答 1查看 2.7K关注 0票数 2

我的问题的一些背景知识:我希望在Json.net中反序列化一些可怕的json。这个json对象是由ArcGIS服务器创建的,它发送一个'results‘对象,其格式如下:

代码语言:javascript
复制
{ "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对象上:

代码语言:javascript
复制
{ "OBJECTID" : "61", "Ward" : "MyWard", "Polling Station" : "Childrens Resources Centre", "Polling District" : "E", "Constituency" : "South", "Shape" : "Polygon" }

...which在某些标识符中有空格;它是由“pretty”字段别名生成的,而不是数据表名。我可以使用linq selectToken来获取所有其他字段,但我要特别查找“投票站”。

我已经尝试了该查询的许多变体:

代码语言:javascript
复制
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,所以我可能犯过一些学生错误。欢迎任何建议!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-07-20 23:03:00

在JPath.cs中读取JPath.ParseMain代码的工作原理是

代码语言:javascript
复制
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中,它没有任何形式的转义:

代码语言:javascript
复制
var pollingStation = (string)jObj.SelectToken("results[0].attributes.Polling Station");
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6763314

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档