如何使用NewtonSoft反序列化对象JSON列表?

6

我可以使用Newtonsoft.Json将以下类序列化,但无法使用Newtonsoft.Json反序列化相同的json。我该怎么做?

Json:

"{\"UserEvents\":[{\"id\":1214308,\"Date\":20150801000000,\"IsRead\":true}]}"

我的实体:

   public class UserEventLog {
    [JsonProperty("UserEvents")]
    public List<UserEvent> UserEvents { get; set; }
    public UserEventLog() {
        UserEvents = new List<UserEvent>();
    }
}


public class UserEvent {
    [JsonProperty("id")]
    public long id{ get; set; }
      [JsonProperty("Date")]
    public long Date{ get; set; }
      [JsonProperty("IsRead")]
    public bool IsRead { get; set; }
}

我的反序列化程序是这样的:
  List<UserEventLog> convert = JsonConvert.DeserializeObject<List<UserEventLog>>(user.ToString()) as List<UserEventLog>;

但是会产生Error

未经处理的异常类型 'Newtonsoft.Json.JsonSerializationException' 在 Newtonsoft.Json.dll 中发生。

其他信息:将值 "{"UserEvents":[{"id":1214308,"Date":20150801000000,"IsRead":true}]}" 转换为类型 'System.Collections.Generic.List`1 的时候出错。

我该如何解决它?如何将我的对象列表反序列化为 UserEvents 列表?


你的 JSON 数据不包含列表,而是一个对象。 - Backs
1
您的示例字符串不是“UserEventLog”的列表。 - crashmstr
1个回答

10

这在linqpad中有效:

void Main()
{
    var user = "{\"UserEvents\":[{\"id\":1214308,\"Date\":20150801000000,\"IsRead\":true}]}";
    UserEventLog convert = JsonConvert.DeserializeObject<UserEventLog>(user.ToString());
    convert.UserEvents.Count().Dump();
}

public class UserEventLog 
{
    [JsonProperty("UserEvents")]
    public List<UserEvent> UserEvents { get; set; }

    public UserEventLog() 
    {
        UserEvents = new List<UserEvent>();
    }
}


public class UserEvent 
{
    [JsonProperty("id")]
    public long id { get; set; }

    [JsonProperty("Date")]
    public long Date { get; set; }

    [JsonProperty("IsRead")]
    public bool IsRead { get; set; }
}

问题是您正在尝试反序列化为列表,但它不是UserEvents数组。

你不需要使用 as UserEventLog,因为 DeserializeObject<T> 返回 T。 - crashmstr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接