.NET Core 3 System.Text.Json 嵌套对象序列化
.NET Core 3 System.Text.Json nested object serialization
刚刚使用 VS2019 web 应用程序模板试用新 System.Text.Json:
有天气预报class声明为:
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;
}
returns 使用 json 对象:{}
如何序列化嵌套对象?
您需要使用属性,可能字段不会序列化。添加获取和设置为预测。
public class TestClass
{
public WeatherForecast Forecast {get;set;}
}
刚刚使用 VS2019 web 应用程序模板试用新 System.Text.Json:
有天气预报class声明为:
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;
}
returns 使用 json 对象:{}
如何序列化嵌套对象?
您需要使用属性,可能字段不会序列化。添加获取和设置为预测。
public class TestClass
{
public WeatherForecast Forecast {get;set;}
}