4

Just playing with new System.Text.Json using VS2019 web application template:

Having weather forecast class declaration as:

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

Example method:

 [HttpGet("Test1")]
    public WeatherForecast Test1()
    {
        WeatherForecast forecast = new WeatherForecast();
        return forecast;
    }

This works ok, returned: {"date":"0001-01-01T00:00:00","temperatureC":0,"temperatureF":32,"summary":null}

But this code:

 public class TestClass
    {
        public WeatherForecast Forecast;
    }

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

returns emply json object: {}

How to serialize nested objects?

4

1 回答 1

4

您需要使用属性可能字段不会序列化。添加获取并设置为预测。

public class TestClass
{
    public WeatherForecast Forecast {get;set;}
}
于 2019-09-26T15:43:51.783 回答