【问题标题】:Deserialize JSon to Payload<List<Post>> using JsonSerializer.Deserialize使用 JsonSerializer.Deserialize 将 JSon 反序列化为 Payload<List<Post>>
【发布时间】:2020-08-24 20:09:55
【问题描述】:

我有以下课程:

public class Post {
  public Int32 Id { get; set; }
  public String Title { get; set; }
}  

public class Payload<T> {
  public IList<Error> Errors { get; private set; }
  public T Result { get; private set; }
}

我有以下 Json:

{
  "result": [
    { "id": 1, "title": "Post 1" },
    { "id": 2, "title": "Post 2" }
  ]
}

我尝试使用以下方法将此 Json 解析为 Payload&lt;List&lt;Post&gt;&gt;

Payload<List<Post>> payload = JsonSerializer.Deserialize<Payload<List<Post>>>(json);

但是,payload.Result 字段为空。我错过了什么?

【问题讨论】:

    标签: c# asp.net-core .net-core asp.net-core-3.1


    【解决方案1】:

    Json 我发现当您反序列化您的项目时,它应该如下所示;

    public class Result
    {
        public int id { get; set; }
        public string title { get; set; }
    }
    
    public class Example
    {
        public IList<Result> result { get; set; }
    }
    

    但我在你的代码中看到了这些;

      public T Result { get; private set; }
    

    也许这不是问题,因为 setter 不是公开的,但我仍然认为说 JsonIgnore 会更容易理解。

    如果你想知道你的 Json 在反序列化后会转换什么对象,你可以看here

    【讨论】:

    • 问题在于使用私有集。我刚刚解决了。感谢您的帮助。
    猜你喜欢
    • 2018-10-06
    • 1970-01-01
    • 2021-06-14
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 2014-02-08
    • 1970-01-01
    相关资源
    最近更新 更多