Newtonsoft JSON反序列化和写入数据

时间:2015-03-13 21:40:39

标签: json json.net

我从下面粘贴的JSON创建了以下Visual Studio类。

public class Rootobject
{
    public Class1[] Property1 { get; set; }
}

public class Class1
{
    public string id { get; set; }
    public string comments { get; set; }
    public DateTime createdDate { get; set; }
    public DateTime modifiedDate { get; set; }
    public string createdBy { get; set; }
    public string modifiedBy { get; set; }
}

- - - - - - - - JSON

[{" id":" 00a17000000LmTOAA0","评论":"这是从代码中添加的评论或注释",& #34; createdDate":" 2015-03-13T15:52:02.000 + 0000"" modifiedDate":" 2015-03-13T15:52:02.000+ 0000"" createdBy":"联系"" modifiedBy":"联系"},{" ID&#34 ;:" 00a17000000LmTTAA0","评论":"这是从代码中添加的评论或注释",#34; createdDate":" 2015-03-13T15:53:19.000 + 0000"" modifiedDate":" 2015-03-13T15:53:19.000 + 0000"" createdBy&#34 ;:"联系"" modifiedBy":"联系"},{" ID":" 00a17000000LmTYAA0",& #34;评论":"这是从代码",#34; createdDate":" 2015-03-13T15:54:29.000 + 0000&#中添加的评论或注释34;," modifiedDate":" 2015-03-13T15:54:29.000 + 0000"" createdBy":"联系",& #34; modifiedBy":"联系"},{" ID":" 00a17000000LmU7AAK""玉米请求":#34;请求者输入的新注释:这是从代码中添加的注释或注释",#34; createdDate":" 2015-03-13T16:39:43.000 + 0000"" modifiedDate":" 2015-03-13T16:39:43.000 + 0000"" createdBy":"联系&#34 ;," modifiedBy":"联系"},{" ID":" 00a17000000LmW3AAK""注释":& #34;从SalesF应用程序添加此评论作为代理"," createdDate":" 2015-03-13T17:37:24.000 + 0000"," modifiedDate&# 34;:" 2015-03-13T17:37:24.000 + 0000"" createdBy":"代理"" modifiedBy":& #34;代理"}]

我正在尝试创建一个对象并执行foreach并获取数据...我不断收到错误无法将JSON数组(例如[1,2,3])反序列化为类型' '因为类型需要JSON对象(例如{“name”:“value”})才能正确反序列化。

我在其他方面尝试过这个:

var jsonResponseNotes = JsonConvert.DeserializeObject<Rootobject>(GetCommentsByID());

任何想法都将非常感谢!!!

2 个答案:

答案 0 :(得分:1)

这是您的对象列表。您需要反序列化。你的代码应该是:

var jsonResponseNotes = JsonConvert.DeserializeObject<List<Class1>>(GetCommentsByID());

修改

注意到你的根对象属性是一个数组。不过,我相信数组会反序列化为列表对象。我调整了我的代码。

答案 1 :(得分:1)

你只需要根类:

public class RootObject
{
    public string id { get; set; }
    public string comments { get; set; }
    public string createdDate { get; set; }
    public string modifiedDate { get; set; }
    public string createdBy { get; set; }
    public string modifiedBy { get; set; }
}

然后将其反序列化:

var result = JsonConvert.DeserializeObject<List<RootObject>>(json);
相关问题