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

标签 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,所以我可能犯了一些小学生错误。欢迎提出任何建议!

最佳答案

阅读 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/

相关文章:

php - 在 PHP 中,如何以 JSON 格式从 MySQL 返回多个列值?

c# - 将 JSON 反序列化为抽象类

c# - 我应该如何在 F# 项目中序列化来自 Refit 的 JSON?

c# - 如何使用 NEST 通过谓词删除所有文档

c# - 重用异步套接字 : subsequent connect attempts fail

c# - (有时)词典中不存在给定的键

json - 针对包含多个模式定义的 JSON 模式进行验证

c# - 如何从 ASP.NET 按钮进行 HTTP POST?

android - 发生异常时的 Robospice 缓存

c# - JSON.NET 在解析集合时忽略空值