System.Text.Json 未序列化 List<T> [英] System.Text.Json not serialising List&lt;T&gt;

查看:39
本文介绍了System.Text.Json 未序列化 List<T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是 .Net 5.

I am just .Net 5.

我正在使用 Blazor 创建一个 QC 应用程序,我正在使用 System.Text.Json 来序列化具有 List 属性的包装器对象,它们是QC问题的答案发布到服务器并保存在数据库中.
但是 List 中的每个项目都没有被序列化,所以发布的请求有一个空的 List .

I am creating a QC app with Blazor and I am using System.Text.Json to serialise a wrapper object that has a property of List<T> which are answers to QC questions that are post to the server and saved in the database.
However each item in the List is not being serialised, so the posted request has a empty List .

所以在我的代码中,我只是对一个对象进行了一个非常简单的序列化:

So in my code I am just doing a very simple serialisation of an object:

string content = JsonSerializer.Serialize(obj);

如果我调试然后我可以看到 Answers 数组具有正确的长度,但每个项目都是空的:
'{Answers":[{},{},{},{}],...}'
但是,C# 对象绝对具有正确输入值的属性.

If I debug then I can see the Answers array has the correct length, but every item is empty:
'{"Answers":[{},{},{},{}],...}'
However, the C# object most definitely do have properties with the correctly entered values.

T 是一个答案对象,它只是一个没有注释的 POCO:

The T is an answer object, it is just a POCO with not annotation:

    public class ReturnedQCResult
    {
        public string Question;
        public int QuestionEntryTypeID;
        public char QuestionType;
        public short QuestionSequence;
        public string Text;
        public decimal? Number;
        public bool? YesNo;
        public DateTime? DateEntry;
        public TimeSpan? TimeEntry;
        public long QuestionID;
    }

有没有人知道为什么会发生这种情况,或者是否有要打开的设置?

Does anyone have any idea as to why this is happening or if there is a setting to turn on?

非常感谢.

推荐答案

虽然以前版本的 System.Text.Json 只能序列化公共属性,但从 .NET 5 开始,您现在可以明确告诉 System.Text.Json 包括序列化中的字段:https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0#include-fields

While previous versions of System.Text.Json could only serialize public properties, as of .NET 5, you can now explicitly tell System.Text.Json to include fields in serialization: https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0#include-fields

var options = new JsonSerializerOptions()
{
    IncludeFields = true,
};
string content = JsonSerializer.Serialize(obj, options);

这篇关于System.Text.Json 未序列化 List<T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆