使用Newtonsoft.JSON解析JSON

时间:2014-01-15 19:16:03

标签: c# .net json json.net

我有一个JSON字符串,如下所示:

[{
    "ID":"1",
    "title":"New Product Launch",
    "fro":"Vitamin D",
    "summary":"New Vitamin D prodcut",
    "type":"image",
    "link":"http:\/\/www.foo.in\/upload\/image\/1.png",
    "detail":"13-11-2013",
    "fileSize":23763
},
{
    "ID":"2",
    "title":"New Product Launch",
    "fro":"Vitamin D",
    "summary":"New Vitamin D prodcut",
    "type":"image",
    "link":"http:\/\/www.foo.in\/upload\/image\/1.png",
    "detail":"13-11-2013",
    "fileSize":23763
}]

我的解析代码如下:

AnnouncementListObject resultsJSON = JsonConvert.DeserializeObject<AnnouncementListObject>(json); //line1

using (AnnouncementDataContext context = new AnnouncementDataContext(Con_String))
{
     AnnouncementData alData = new AnnouncementData();
     alData.announcementID = int.Parse(resultsJSON.ID);
             .
             .
             .
             .
       context.AnnouncementData.InsertOnSubmit(alData);
       context.SubmitChanges();
}

修改

public class AnnouncementListObject
{
    public string ID { get; set; }
    public string title { get; set; }
    public string fro { get; set; }
    public string summary { get; set; }
    public string type { get; set; }
    public string link { get; set; }
    public string detail { get; set; }
    public object fileSize { get; set; }
}

但它在第1行抛出错误,我在其中反序列化JSON数据。我想将这多个数据行存储在数据库中。我不能在这里使用foreach循环,因为JSON数据不包含在根节点下。我该怎么办?

1 个答案:

答案 0 :(得分:3)

尝试反序列化为类似的列表

var resultsJSON = JsonConvert.DeserializeObject<List<AnnouncementListObject>>(json); //line1

您正在处理一组JSON对象,但您正在尝试将其作为单个对象进行投射。