反序列化JSON对象C#prob

时间:2014-08-22 18:46:13

标签: c# json serialization

我有以下Json片段:

Article: [
{
@attributes: {
id: "10819"
},
title: "Weekend Guide and Previews",
county1: { },
county2: { },
newsid: "10819",
sections: {
section_id: [
"13",
"1"
]
},
content_text_id: "8561",
content_image_id: "6626",
content_video: "NONE",
upload_date: "2014-08-22 10:16:39",
filename: "http://www.gaa.ie/content/images/news/mayo/OSheaAidan_v_Kerry.jpg",
thumbnail: "http://www.gaa.ie/content/content_thumbs/Images/news/mayo/OSheaAidan_v_Kerry.jpg",
url: "http://www.gaa.ie/gaa-news-and-videos/daily-news/1/2208141016-weekend-guide-and-previews/1/"
},
{
@attributes: {
id: "10825"
},
title: "Press Release: Weekend Travel Information",
county1: { },
county2: { },
newsid: "10825",
sections: {
section_id: [
"13",
"1"
]
},
content_text_id: "8567",
content_image_id: "6396",
content_video: "NONE",
upload_date: "2014-08-22 17:05:13",
filename: "http://www.gaa.ie/content/images/news/croke_park/CrokePark_general_view2014.jpg",
thumbnail: "http://www.gaa.ie/content/content_thumbs/Images/news/croke_park/CrokePark_general_view2014.jpg",
url: "http://www.gaa.ie/gaa-news-and-videos/daily-news/1/2208141705-press-release-weekend-travel-information/1/"
}
]

和以下文章类:

public class Article
    {
        public int newsid { get; set; }
        public String title { get; set; }
        public String content_text_id { get; set; }
        public String content_image_id { get; set; }
        public DateTime upload_date { get; set; }
        public String filename { get; set; }
        public String thumbnail { get; set; }
        public String url { get; set; }
        public String content_video { get; set; }

    }

我正在尝试将json反序列化为文章如下:

var obj = JsonConvert.DeserializeObject<List<Article>>(json);

我收到以下错误:

  

无法将当前JSON对象(例如{&#34; name&#34;:&#34; value&#34;})反序列化为类型System.Collections.Generic.List`1 [MvcApplication2.Models .Article]&#39;因为该类型需要JSON数组(例如[1,2,3])才能正确反序列化。要修复此错误,请将JSON更改为JSON数组(例如[1,2,3])

我也无法理解名为@attributes的属性?虽然对我来说不是必需的,但是属性也是如此。

1 个答案:

答案 0 :(得分:2)

有两个问题

json中的数组应定义为

enter image description here

但是你的json不是数组定义。它甚至不是对象定义。要使其成为有效的数组定义,您应该从json中删除Article:

第二个问题是@个字符。 JSON.NET不适用于它们,因此您应该删除或替换这些字符:

json = json.Replace("Article:", "").Replace("@attributes", "attributes");
var articles = JsonConvert.DeserializeObject<List<Article>>(json);

结果:

enter image description here