Reputation: 23
Some background to my question: I'm looking to deserialize some horrid json within Json.net. This json object is created by ArcGIS Server, and sends a 'results' object which is formatted thusly:
{ "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" } } ] }
Now the problem is the attributes object:
{ "OBJECTID" : "61", "Ward" : "MyWard", "Polling Station" : "Childrens Resources Centre", "Polling District" : "E", "Constituency" : "South", "Shape" : "Polygon" }
...which has whitespace in some identifiers; it's being generated by the 'pretty' field alias, and not the data table name. I'm able to use the linq selectToken to get all other fields, but I'm looking for "Polling Station" in particular.
I've tried quite a few variants of the query:
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)
I've googled, searched the json.net help & read quite a few questions already posted here - none of which seem to deal with this particular question. Maybe I'm just being dense. You may also be able to tell I'm not proficient in c#, or Linq, and this is the first time I've used Json.net so I have probably made some schoolboy errors. Any suggestions welcome!
Upvotes: 2
Views: 3326
Reputation: 17837
Reading the JPath.ParseMain
code in JPath.cs
what works is
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']");
Remark: in pre-2013 JSon.Net it worked without any form of escaping :
var pollingStation = (string)jObj.SelectToken("results[0].attributes.Polling Station");
Upvotes: 2