I have a class defined as follows:
public class NearestLocation
{
public Int32 ID { get; set; }
public String Name { get; set; }
public String TypeID { get; set; }
public String SourceID { get; set; }
public String Code { get; set; }
public Double Latitude;
public Double Longitude;
public Int32? Distance { get; set; }
public String Direction { get; set; }
public String Relative { get; set; }
public DateTime? LastUpdatedOn { get; set; }
}
and a string jsonData
returned from an API call that contains the following JSON:
{\"Latitude\":-45.861900329589844,\"Longitude\":170.36294555664063,\"Distance\":13,\"Direction\":\"E\",\"Relative\":\"Helicopters Otago (South)\",\"ID\":413,\"Code\":\"HOLS\",\"Name\":\"Helicopters Otago (South)\",\"TypeID\":\"helipad\",\"SourceID\":\"holcwh\",\"LastUpdatedOn\":\"2022-05-08T23:18:41.987\"}
When I deserialize jsonData
into an object as follows:
NearestLocation nearest = JsonSerializer.Deserialize<NearestLocation>(jsonData);
nearest
is only partially populated:
Code: "HOLS"
Direction: "E"
Distance: 13
ID: 413
LastUpdatedOn: {8/05/2022 11:18:41 pm}
Latitude: 0
Longitude: 0
Name: "Helicopters Otago (South)"
Relative: "Helicopters Otago (South)"
SourceID: "holcwh"
TypeID: "helipad"
Why are Latitude
and Longitude
not being populated? I can see the correct values in the JSON, and other values - of types String, Int32 and DateTime - are all being populated correctly. It is only the doubles that are not being populated correctly.
I don't seem to be able to trace into JsonSerializer
to see what's going on under the hood - the debugger just steps over the line. I've checked the names in the JSON and in the class definition to make sure they match - which they do - but I am at a loss to understand why this is happening.
Latitude
and Longitude
are fields. Adding getter and setter in order to convert them to properties.
public class NearestLocation
{
// Other properties
public double Latitude { get; set; }
public double Longitude { get; set; }
}
From the documentation,
By default, fields are ignored. You can include fields.
To include field for serialization/deserialization, you need to apply the [JsonInclude]
attribute as mentioned.