gipo
gipo

Reputation: 19

Deserialize JSON Object C# prob

I have the following snippet of 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/"
}
]

and the following Article class:

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; }

    }

I am trying to deserialize the json to articles as follows:

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

I get the following error:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[MvcApplication2.Models.Article]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3])

I also have trouble understanding the property called @attributes? Although is not necessary for me, as is the sections property.

Upvotes: 1

Views: 83

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

There are two problems

Arrays in json should be defined as

enter image description here

But your json is not an array definition. It's even not object definition. To make it valid array definition you should remove Article: from your json.

Second problem is @ characters. JSON.NET not works with them, so you should remove or replace these characters:

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

Result:

enter image description here

Upvotes: 2

Related Questions