System.Text.Json反序列化TimeStamp属性值为null的异常问题
System.Text.Json反序列化TimeStamp属性为null的问题解决
问题场景
我的StagingModel模型类定义如下:
public class StagingModel { public string? TableName { get; set; } public string? ConnectionName { get; set; } public long? TimeStamp { get; set; } public Dictionary<string, object>? Data { get; set; } = []; }
使用System.Text.Json进行反序列化的代码:
StagingModel stagingModel = JsonSerializer.Deserialize<StagingModel>(message);
用于复现问题的JSON字符串:
{ "TableName":"position", "ConnectionName":"TestDat", "Timestamp":1708538002240, "Data":{ "gpslatitude":54.719564167, "gpslongitude":11.448629 }, "TopicName":"kafka" }
实际测试发现:用System.Text.Json反序列化时,TimeStamp属性的值始终为null;但换用Newtonsoft.Json处理同一段JSON,该属性能正常获取到值。
原因分析
System.Text.Json默认采用精确大小写匹配的规则,而Newtonsoft.Json默认支持驼峰式的大小写不敏感匹配。你的JSON里字段是Timestamp(小写s),但模型类的属性是TimeStamp(大写S),两者大小写不一致,导致System.Text.Json无法匹配到对应属性,最终赋值为null。
解决方案
方法1:修改JSON字段名(如果可修改)
把JSON中的Timestamp改为和模型属性完全一致的TimeStamp:
{ "TableName":"position", "ConnectionName":"TestDat", "TimeStamp":1708538002240, "Data":{ "gpslatitude":54.719564167, "gpslongitude":11.448629 }, "TopicName":"kafka" }
方法2:给模型属性添加JsonPropertyName特性
在TimeStamp属性上标注特性,指定它对应的JSON字段名:
public class StagingModel { public string? TableName { get; set; } public string? ConnectionName { get; set; } [JsonPropertyName("Timestamp")] public long? TimeStamp { get; set; } public Dictionary<string, object>? Data { get; set; } = []; }
方法3:配置JsonSerializerOptions启用大小写不敏感匹配
反序列化时传入配置选项,开启全局的大小写不敏感匹配:
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; StagingModel stagingModel = JsonSerializer.Deserialize<StagingModel>(message, options);
内容的提问来源于stack exchange,提问作者Sadaqat
相关产品推荐
相关产品推荐

