为何JsonSerializer反序列化仅部分填充对象?Latitude和Longitude未赋值
问题:JsonSerializer反序列化时Double字段未正确赋值
定义的C#类
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; } }
API返回的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"}
反序列化代码
NearestLocation nearest = JsonSerializer.Deserialize<NearestLocation>(jsonData);
问题原因
Latitude和Longitude是普通字段,而System.Text.Json的默认规则是仅序列化/反序列化带get/set访问器的属性,不会处理普通字段,因此这两个字段无法被JSON数据赋值,保持默认的0值。
解决方法
方法1:将字段改为属性(推荐)
把Latitude和Longitude修改为标准属性,适配System.Text.Json的默认行为,同时符合C#封装规范:
public class NearestLocation { // ... 其他成员保持不变 public Double Latitude { get; set; } public Double Longitude { get; set; } // ... 其他成员保持不变 }
方法2:配置序列化选项包含字段
如果无法修改类定义,可以在反序列化时指定IncludeFields选项,让序列化器处理字段:
var options = new JsonSerializerOptions { IncludeFields = true }; NearestLocation nearest = JsonSerializer.Deserialize<NearestLocation>(jsonData, options);
内容的提问来源于stack exchange,提问作者ChrisH
相关产品推荐
相关产品推荐

