【问题标题】:How can you deserialize a JSON string using JSON.NET that uses empty quotes rather than null for a field如何使用 JSON.NET 反序列化 JSON 字符串,该字符串对字段使用空引号而不是 null
【发布时间】:2011-10-18 19:05:45
【问题描述】:

我正在尝试使用 JSON.NET 反序列化一些 reddit cmets(以 JSON 格式返回)。我遇到了一个问题,评论有一个“回复”字段,它要么是另一个评论对象,要么是空引号 ("")。问题是 JSON.NET 反序列化器在反序列化期望对象但找到“”的字段时抛出异常(正如我所期望的那样,它正在寻找 null 而不是“”)。

例子:

"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"

   }

然后这是:

"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

有没有办法用 JSON.NET 反序列化它,还是我必须做一个正则表达式来搜索 "Replies": "" 以将所有这些空引号更改为 null?

谢谢!

【问题讨论】:

  • 我将不得不看一下 - 我相信如果值为 null 就可以了,但是“”会导致问题,也许我可以让反序列化器处理“ " 虽然为 null,但感谢您的提示!

标签: .net json json.net deserialization


【解决方案1】:

这里的问题是与“回复”属性关联的类型是动态的:它是字符串或 JSON 对象。如果您使用的是 .NET 4.0,则应使用 dynamic 关键字来反映数据的动态性质。如果您使用的是其他版本的 .NET,您可以反序列化为 Newtonsoft.Json.Linq.JObject。以here 为例。祝你好运。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多