I am trying to deserialize some reddit comments (returned in JSON) using JSON.NET. I have come across a problem where the Comment has a field “Replies”, which is either another Comment object, or empty quotes (“”). The problem is the JSON.NET deserializer throws an exception when deserializing a field that is expecting an object but finds “” (as I expect it is looking for null rather than “”).
Example:
"data":{
"body":"We were being trolled. ",
"subreddit_id":"t5_2qh1i",
"author_flair_css_class":null,
"created":1318984933.0,
"author_flair_text":null,
"downs":1,
"author":"evange",
"created_utc":1318959733.0,
"body_html":"<div class=\"md\"><p>We were being trolled.</p></div>",
"levenshtein":null,
"link_id":"t3_lghhj",
"parent_id":"t3_lghhj",
"likes":null,
"replies":"",
"id":"c2shf1a",
"subreddit":"AskReddit",
"ups":6,
"name":"t1_c2shf1a"
}
And then this is the :
"data":{
"body":"Dude, it was a Roll Troll. Forget it.",
"subreddit_id":"t5_2qh1i",
"author_flair_css_class":null,
"created":1318985233.0,
"author_flair_text":null,
"downs":1,
"author":"youngmonk",
"created_utc":1318960033.0,
"body_html":"<div class=\"md\"><p>Dude, it was a Roll Troll. Forget it.</p></div>",
"levenshtein":null,
"link_id":"t3_lghhj",
"parent_id":"t3_lghhj",
"likes":null,
"replies":{
"kind":"Listing",
"data":{
"modhash":"",
"children":[....etc
Is there a way to deserialize this with JSON.NET, or will I have to do a RegEx to search for “Replies”: “” to change all those empty quotes to null?
Thanks!
The issue here is that the type associated with the “replies” property is dynamic: it is either a string or a JSON object. If you are using .NET 4.0 you should use the dynamic keyword to reflect the dynamic nature of the data. If you are using another version of .NET you can deserialize into a Newtonsoft.Json.Linq.JObject. Look here for an example. Best of luck.