Home > Software engineering >  .Net 6 `JsonPropertyName` deserialisation not working
.Net 6 `JsonPropertyName` deserialisation not working

Time:11-30

I am trying to use System.Text.Json to serialize/deserialize some API response, and the JSON fields aren't exactly the same as the C# classes I am working with so for the actual names I tried using JsonPropertyName but it didn't seem to work like intended. I tried going back to .Net documentation, and use one of their examples to check where I had the problem, but the deserialisation still didn't go through.
Here's the sample code I used:

var json =
    @"{""dit_date"":""2020-09-06T11:31:01.923395"",""temperature_c"":-1,""sum_mary"":""Cold""} ";
Console.WriteLine($"Input JSON: {json}");

var forecast = JsonSerializer.Deserialize<Forecast>(json)!;

Console.WriteLine($"forecast.Date: {forecast.Date}");
Console.WriteLine($"forecast.TemperatureC: {forecast.TemperatureC}");
Console.WriteLine($"forecast.Summary: {forecast.Summary}");

var roundTrippedJson =
    JsonSerializer.Serialize(forecast);

Console.WriteLine($"Output JSON: {roundTrippedJson}");

The Forecast class:

public class Forecast
{
    [JsonPropertyName("dit_date")] public DateTime Date;
    [JsonPropertyName("temperature_c")] public int TemperatureC;
    [JsonPropertyName("sum_mary")] public string? Summary;
}

And the output I got:

Input JSON: {"dit_date":"2020-09-06T11:31:01.923395","temperature_c":-1,"sum_mary":"Cold"} 
forecast.Date: 01/01/0001 00:00:00
forecast.TemperatureC: 0
forecast.Summary: 
Output JSON: {}

Any idea what's wrong with this?

CodePudding user response:

The class members should be properties, not fields:

public class Forecast
{
    [JsonPropertyName("dit_date")] 
    public DateTime Date { get; set; }

    [JsonPropertyName("temperature_c")] 
    public int TemperatureC { get; set; }

    [JsonPropertyName("sum_mary")] 
    public string? Summary { get; set; }
}
  • Related