0
{
    "id" : 0,
    "name" : "meeting",
    "text" : "10 pm",
    "location" : "Place1",
    "startdate" : "10/27/2012 17:11",
    "enddate" : "10/27/2012 18:41",
    "description" : "Description",
    "chairman" : "0",
    "members" : [2, 1],
    "messagetype" : {
        "SMS" : false,
        "Email" : true
    },
    "smsmessage" : null,
    "emailmessage" : "this is message",
    "emailsubject" : null,
    "reminder" : "5",
    "timetosendemail" : "10/23/2012 00:00",
    "timetosendsms" : null
}

这是我的 json 字符串。我需要的是解析这个字符串并将每个值存储到类的特定成员中。

课堂是这样的

public class Event
{

    public int id { get; set; }
    public string name {get;set;}
    public string text { get; set; }
    public DateTime start_date { get; set; }
    public DateTime end_date { get; set; }
    public string location { get; set; }
    public double ReminderAlert { get; set; }
    public MessagerType MessageType { get; set; }
    public string SmsMessage { get; set; }
    public string EmailMessage { get; set; }
    public string EmailSubject { get; set; }
    public DateTime TimeToSendEmail { get; set; }
    public DateTime TimeToSendSMS { get; set; }   
    public string[] members {get;set;}
}

我使用 Json.net 库来解析..我的代码片段如下所示

var eventValues = JsonConvert.DeserializeObject<List<Dictionary<string, Event>>>(stringEvent);

运行此代码后,我收到此错误

无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.List 1[System.Collections.Generic.Dictionary2[System.String,CalendarScheduler.Models.Event]]”,因为该类型需要 JSON 数组(例如 [1,2,3]) 以正确反序列化。

要修复此错误,要么将 JSON 更改为 JSON 数组(例如 [1,2,3]),要么将反序列化类型更改为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型可以从 JSON 对象反序列化的数组或列表。JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。

路径“id”,第 1 行,位置 6。

应该怎么做才能避免这种异常......?

4

2 回答 2

2

这不行吗?

var eventValues = JsonConvert.DeserializeObject<Event>(stringEvent);

并考虑 Oded 的评论。并将所有 JSON 属性名称与 C# 属性名称匹配。

于 2012-10-27T11:00:55.030 回答
0

试试这个:

public T Deserialize<T>(string json)
{
    T obj = Activator.CreateInstance<T>();
    MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    obj = (T)serializer.ReadObject(ms);
    ms.Close();
    return obj;
}

Event MyEvent = Deserialize<Event>(jsonString);
于 2012-10-27T14:10:49.743 回答