Reputation: 5259
I am using Json.NET in order to parse a json string but when i try to use SelectToken it returns null. Also it seems that Json.NET read the json string as 1 node
here is the JSON
[
[{
"input_index":0,
"candidate_index":0,
"delivery_line_1":"124 Main St",
"last_line":"Cambridge MA 02138-5813",
"delivery_point_barcode":"021385813991",
"components":{
"primary_number":"125",
"street_name":"Main",
"street_suffix":"St",
"city_name":"Cambridge",
"state_abbreviation":"MA",
"zipcode":"02138",
"plus4_code":"5813",
"delivery_point":"99",
"delivery_point_check_digit":"1"
},
"metadata":{
"record_type":"H",
"county_fips":"25017",
"county_name":"New York",
"carrier_route":"C025",
"congressional_district":"08",
"building_default_indicator":"Y"
},
"analysis":{
"dpv_match_code":"D",
"dpv_footnotes":"AAN1",
"dpv_cmra":"N",
"dpv_vacant":"N",
"ews_match":false,
"footnotes":"A#H#N#"
}
}]
]
and here is the code
JArray o = JArray.Parse(page);
string something = (string)o.SelectToken("county_name");
However it just returns me null and i am totally confused as there is something wrong with JSON.NET parsing this Json string
Upvotes: 2
Views: 5477
Reputation: 21245
See: What is the JSON.NET equivalent of XML's XPath, SelectNodes, SelectSingleNode?
var data = GetJson();
//You can use the SelectToken to get the value similar to XPath.
var value = JArray.Parse(data)
.SelectToken("[0][0].metadata.county_name")
.Value<string>();
This can be extended to support multiple elements:
var jArray = JArray.Parse(data);
var countyNames = new List<string>();
foreach(var element in jArray.SelectToken("[0]"))
{
var value = element.SelectToken("metadata.county_name").Value<string>();
countyNames.Add(value);
}
Upvotes: 2
Reputation: 5575
So, the issue is that you basically have a wrapper around your actual object. You basically have:
Array of objects
Object
Metadata
etc
So basically, get the first JToken
out of the JArray
and access the metadata from there.
Upvotes: 0