Deserializing Json list of objects
Published:
I am currently working to finish up Pocket Api wrapper for C#/.Net. In turned out that the Api returned list of articles/items in Json and the list is not in array form. It is actually a list of object. We will see how we can deserialize this using Json.net
First of all it should be straight forward to do this if it returns an array of article. However, this is the Json that was returned. I deprecated some of the code/response to make it brief.
{ "complete" : 1,
"list" : { "332222557" : { "excerpt" : "The second quarter of 2013 started with the bang. Key fundamental shifts in monetary policy and underlying changes in various economies caused a significant increase in volatility across the foreign exchange market.",
"given_title" : "MY Favorite 3 FX Trades for Q2 - bkassetmanagement.com/?p=4424 #forex #usd ",
"is_article" : "1",
"is_index" : "0",
"item_id" : "332222557",
"resolved_id" : "332222557",
"resolved_title" : "Top 3 Forex Trades for Q2",
"sort_id" : 1,
"status" : "0",
},
"341196654" : { "excerpt" : "With no major U.S. or European economic data on the calendar today, currency pairs such as the EUR/USD and USD/JPY failed to break key levels. For EUR/USD, traders are itching for a reason to take the currency pair below 1.",
"given_title" : "http://www.bkassetmanagement.com/?p=4560",
"is_article" : "1",
"is_index" : "0",
"item_id" : "341196654",
"resolved_id" : "341196654",
"resolved_title" : "EUR Break of 1.30 Hinges Upon PMIs",
"sort_id" : 0,
"status" : "0",
}
},
"since" : 1367131079,
"status" : 1
}
To solve this, just treat it as Dictionary or Key-Value-Pair relationship. So, with Json.net, the class correspond to this should be something like this.
public class Pocket
{
[JsonProperty("status")]
public int Status { get; set; }
[JsonProperty("complete")]
public int Complete { get; set; }
[JsonProperty("since")]
public int Since { get; set; }
[JsonProperty("list")]
public IDictionary<string, Article> List { get; set; }
}
public class Article
{
// Some other properties here
// Deprecated coz its too long
[JsonProperty("status")]
public int Status { get; set; }
[JsonProperty("excerpt")]
public string Excerpt { get; set; }
[JsonProperty("is_article")] private int _isArticle;
public bool IsArticle
{
get { return _isArticle == 1 ? true : false; }
set { _isArticle = value ? 1 : 0; }
}
}
Then just call it like this
var converted = JsonConvert.DeserializeObject<Pocket>(json);