我通过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>;
但错误产生:
Newtonsoft.Json.dll中发生未处理的“Newtonsoft.Json.JsonSerializationException”类型异常
其他信息:将值
"{"UserEvents":[{"id":1214308,"Date":20150801000000,"IsRead":true}]}"
转换为类型'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
的数组