Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.Net 6 `JsonPropertyName` deserialisation not working

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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; }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading