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

时间:2015-09-28 14:03:32

标签: c# json serialization json.net

我在Newtonsoft.Json下面的类下面序列化,但我不能通过Newtonsoft.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>;

错误已生成:

  

类型&#39; Newtonsoft.Json.JsonSerializationException的未处理异常&#39;发生在Newtonsoft.Json.dll

     

其他信息:将值"{"UserEvents":[{"id":1214308,"Date":20150801000000,"IsRead":true}]}"转换为&#39; System.Collections.Generic.List`1

时出错

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

1 个答案:

答案 0 :(得分:6)

这适用于linqpad:

mReactInstanceManager = ReactInstanceManager.builder()
        .setApplication(getApplication())
        .setBundleAssetName("index.android.bundle")
        .setJSMainModuleName("src/index.android")
        .addPackage(new MainReactPackage())
        .addPackage(new CustomReactPackage(this)) // <--- LIKE THIS!
        .setUseDeveloperSupport(BuildConfig.DEBUG)
        .setInitialLifecycleState(LifecycleState.RESUMED)
        .build();

问题是您正在尝试反序列化到列表中,但它不是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; } } 的数组

相关问题