Reputation: 105
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?
Upvotes: 4
Views: 2735
Reputation: 1371
You need to use properties probably fields won't serialise. Add get and set to forecast.
public class TestClass
{
public WeatherForecast Forecast {get;set;}
}
Upvotes: 4