1

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!

2
  • Have you looked into JSON.net's NullValueHandling settings? Commented Oct 19, 2011 at 0:42
  • I will have to take a look at that - I believe if the value was null it would be ok, but the ""'s are causing an issue, maybe I can get the deserializer to treat "" as null though, thanks for the tip! Commented Oct 19, 2011 at 1:42

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.