【问题标题】:Deserializing json with Json.net C# - whitespace within identifiers使用 Json.net C# 反序列化 json - 标识符中的空格
【发布时间】:2011-07-20 14:10:39
【问题描述】:

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

【问题讨论】:

  • 这与LINQ无关
  • 使用SelectToken吗?您可以只使用索引器来获取单个值吗?这就是我一直在做的事情。
  • SLaks:对不起 - 我的印象是 SelectToken 在 Newtonsoft.Json.Linq 命名空间中。不是。
  • Jon:不,我不必使用 SelectToken - 我认为这是获取特定元素而不将整个事物反序列化为对象的最简单方法。您能否详细说明我将如何以另一种方式进行操作?我应该在哪里查看 Json.net 文档?

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


【解决方案1】:

阅读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");

【讨论】:

  • 不错。我什至不认为它会“正常工作”而不必被引用、括起来或以其他方式转义。谢谢!
  • 其实读代码,没有什么是逃避不了的。这意味着无法通过此 API 访问某些正确的 json 属性名称,例如“x[.3”(属性名称是 json 中的任意 unicode 字符串)。
  • 这个答案最初发布在这里四年后,我无法让它在 Newtonsoft.Json 7.0.0 中工作。我收到一条错误消息,指出存在“无效字符”。就我而言,这始终发生在空格中。
  • json.net 在 2013 年改变了他们的格式,现在是 attributes.['Polling Station'] 我会更新我的答案。
  • 感谢您的帮助,@Julien。我将看到将其添加到官方文档中。截至目前,我在那里没有看到任何关于它的信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多