<Post>使用 JsonSerializer 将 JSon 反序列化为 Payload<List>。



我有以下类:

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<List<Post>>

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

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

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在反序列化后将转换什么对象,可以查看此处。

最新更新