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

4

我正在尝试使用VS2019 Web应用程序模板,玩弄新的System.Text.Json

有天气预报类声明如下:

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;
    }

返回空的JSON对象: {}

如何序列化嵌套对象?

1个回答

4

您需要使用属性,可能字段无法序列化。在 forecast 中添加 get 和 set。

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

1
完全相同的问题。一个模型上错过了getter和setter。我都快抓狂了。谢谢! - Francisco d'Anconia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接