我正在尝试使用JSON.NET反序列化一些reddit注释(以JSON格式返回)。我遇到了一个问题,其中Comment有一个字段“Replies”,它是另一个Comment对象,或者是空引号(“”)。问题是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反序列化,或者我是否必须使用RegEx来搜索“回复”:“”将所有空引号更改为null?
谢谢!
答案 0 :(得分:0)
这里的问题是与“replies”属性关联的类型是动态的:它是字符串或JSON对象。如果您使用的是.NET 4.0,则应使用dynamic关键字来反映数据的动态特性。如果您使用的是其他版本的.NET,则可以反序列化为Newtonsoft.Json.Linq.JObject。查看here示例。祝你好运。