gpt4 book ai didi

c# - 如何通过 NewtonSoft 反序列化对象 json 列表?

转载 作者:行者123 更新时间:2023-11-30 14:27:27 24 4
gpt4 key购买 nike

我通过 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>;

但是产生了错误:

An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll

Additional information: Error converting value "{"UserEvents":[{"id":1214308,"Date":20150801000000,"IsRead":true}]}" to type 'System.Collections.Generic.List`1

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

最佳答案

这在 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 的数组

关于c# - 如何通过 NewtonSoft 反序列化对象 json 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32825018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com