【问题标题】:.NET Core 3 System.Text.Json nested object serialization.NET Core 3 System.Text.Json 嵌套对象序列化
【发布时间】:2020-01-26 22:09:57
【问题描述】:

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

返回 emply json 对象:{}

如何序列化嵌套对象?

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 完全相同的问题。在一个模型上错过了 getter 和 setter。正在拉我的头发。谢谢!
    猜你喜欢
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多