I'm calling JsonSerializer.Deserialize(ref reader, options)
, but for some reason it isn't working.
public class WeatherForecastJsonConverter : JsonConverter<WeatherForecast>
{
public override WeatherForecast? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// Returns an empty WeatherForecastData
var data = JsonSerializer.Deserialize<WeatherForecastData>(ref reader, options);
return new WeatherForecast
{
Date = data.Date,
TemperatureCelsius = data.TC,
Summary = data.Summary == 1 ? "Hot" : data.Summary == -1 ? "Cold" : string.Empty,
};
}
public override void Write(Utf8JsonWriter writer, WeatherForecast value, JsonSerializerOptions options)
{
var data = new WeatherForecastData(value.Date, value.TemperatureCelsius, value.Summary ?? string.Empty);
JsonSerializer.Serialize(writer, data, options);
}
}
Below are the data types I use. The idea is that calling JsonSerializer.Serialize<WeatherForecast>(...)
and JsonSerializer.Deserialize<WeatherForecast>(...)
will generate an optimized json all on its own.
[JsonConverter(typeof(WeatherForecastJsonConverter))]
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureCelsius { get; set; }
public string? Summary { get; set; }
}
internal readonly struct WeatherForecastData
{
public DateTime Date { get; }
public int TC { get; }
public int Summary { get; }
public WeatherForecastData(DateTime date, int temperatureCelsius, string summary)
{
this.Date = date;
this.TC = temperatureCelsius;
this.Summary = summary == "Hot" ? 1 : summary == "Cold" ? -1 : 0;
}
}
My test code is:
// This works
[Fact]
public void TestSerialize()
{
var weatherForecast = new WeatherForecast
{
Date = System.DateTime.Parse("1731-02-08T00:00:00"),
TemperatureCelsius = 2,
Summary = "Cold"
};
var json = JsonSerializer.Serialize(weatherForecast);
}
// This doesn't
[Fact]
public void TestDeserialize()
{
var json = "{\"Date\":\"2019-08-01T00:00:00\",\"TC\":25,\"Summary\":1}";
var weatherForecast = JsonSerializer.Deserialize<WeatherForecast>(json);
}
I was expecting this to work, why it's failing me I have no idea. I have read the documentation on UTF8JsonReader usage but see no information on JsonSerializer.Deserialize(ref reader)
. I'm kindof stumped.
The problem is because your target class is readonly, I changed and it works.
internal struct WeatherForecastData
{
public DateTime Date { get; set; }
public int TC { get; set; }
public int Summary { get; set; }
public WeatherForecastData(DateTime date, int temperatureCelsius, string summary)
{
this.Date = date;
this.TC = temperatureCelsius;
this.Summary = summary == "Hot" ? 1 : summary == "Cold" ? -1 : 0;
}
}