DharaPPatel DharaPPatel - 5 months ago 61
JSON Question

Deserialize JSON in c# when the return dataset in not known

I am working on census data and the url for my json is:

http://api.census.gov/data.json

From the above json i want to build the drop down of "title" where "c_dataset" have "acs5". Now the code in my MVC controller is as follows :

var yourObject = new JavaScriptSerializer().Deserialize<dynamic>(result.ToString());

foreach (KeyValuePair<string, object> currency in yourObject)
{
if (currency.Key == "dataset")
{
foreach (KeyValuePair<string, object> cur in currency.Value)
{

}
}
}


the inner most foreach gives me an error that "foreach statement can not operate on variable type 'object' because 'object' does not contain a public definition for 'GetEnumerator' !! i can not deserialize the object in certain class because this json is big. What could be the best way to do this ? Also, i was wondering if i can use the LINQ to query the deserialize object. Thanks in advance.

Answer

I think your best bet would be to build concrete type(s) that only have the properties you want, ignoring everything else. JSON deserializer will then ignore additional "noise" and only read the properties you specified.

// not tested
class CensusDataSet
{
    [JsonProperty("c_dataset")]
    public string[] CDataset { get; set; }

    [JsonProperty("title")]
    public string Title { get; set; }
}

class CensusData
{

    [JsonProperty("dataset")]
    public CensusDataSet[] DataSets { get; set; }
}

...
var data = Newtonsoft.Json.JsonConvert.DeserializeObject<CensusData>(content);

foreach (var dataSet in data.DataSets) ...

BTW, your title is misleading: what you are trying to do is called deserialize.