.NET Core 3 System.Text.Json 嵌套对象序列化

标签 .net json asp.net-core .net-core system.text.json

刚玩新System.Text.Json使用 VS2019 Web 应用程序模板:

将天气预报类声明为:

using System;

namespace WebApplication4
{
    public class WeatherForecast
    {
        public DateTime Date { get; set; }
        public int TemperatureC { get; set; }
        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
        public string Summary { get; set; }
    }
}

示例方法:
 [HttpGet("Test1")]
    public WeatherForecast Test1()
    {
        WeatherForecast forecast = new WeatherForecast();
        return forecast;
    }

这工作正常,返回:
{"date":"0001-01-01T00:00:00","temperatureC":0,"temperatureF":32,"summary":null}

但是这段代码:
 public class TestClass
    {
        public WeatherForecast Forecast;
    }

    [HttpGet("Test")]
    public TestClass Test()
    {
        WeatherForecast forecast = new WeatherForecast();
        TestClass test = new TestClass()
        {
            Forecast = forecast
        };
        return test;
    }

返回 emply json 对象:{}

如何序列化嵌套对象?

最佳答案

您需要使用的属性可能字段不会序列化。添加 get 和 set 以进行预测。

public class TestClass
{
    public WeatherForecast Forecast {get;set;}
}

关于.NET Core 3 System.Text.Json 嵌套对象序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58120037/

相关文章:

json - 解析大型单行 JSON 而无需将整个文件加载到内存中

c# - Entity Framework Core "The entity type ' XXX'需要定义主键。”

c# - Where 子句中的 LINQ 子查询在 LINQPad 中返回错误

.net - 使用 .Net 开发 Robocode 类型的游戏,用于学校作业

javascript - 错误类型错误 : Cannot read property '0' of null | Angular 7

javascript - ng-repeat 不适用于嵌套 json

.net - Appsettings.json 不同版本?

c# - 列映射到未命名列

c# - 当托管在 VSTO/Outlook 加载项中的 ElementHost 中时,WPF 文本框不允许撤消

c# - 设计类结构映射关系数据库的基本规则是什么?