为何JsonSerializerContext对含[ObservableProperty]的模型生成空JSON?
问题原因
JsonSerializerContext依赖静态源生成器提前收集类型的序列化信息,但CommunityToolkit.Mvvm通过[ObservableProperty]生成的自动属性是在编译后期注入到partial类中的,静态源生成器无法自动识别这些动态生成的属性,导致生成的TypeInfo中不包含IP、Port等属性,最终序列化时仅输出类型标识。
解决方案
在每个[ObservableProperty]修饰的字段上添加[property: JsonInclude]特性,明确告知Json源生成器要包含动态生成的对应属性。
修改后的核心代码示例:
public partial class EthernetConnection : EmptyConnection { [ObservableProperty] [property: JsonInclude] // 添加此特性 string _IP = ""; [ObservableProperty] [property: JsonInclude] // 添加此特性 int _Port = 0; } public partial class SerialPortConnection : EmptyConnection { [ObservableProperty] [property: JsonInclude] string _PortName = ""; [ObservableProperty] [property: JsonInclude] int? _BaudRate = null; [ObservableProperty] [property: JsonInclude] Parity? _Parity = null; [ObservableProperty] [property: JsonInclude] int? _DataBits = null; [ObservableProperty] [property: JsonInclude] StopBits? _StopBits = null; [ObservableProperty] [property: JsonInclude] string _PortFeature = ""; }
补充说明
- 不使用
TypeInfoResolver时,System.Text.Json会通过反射动态获取类型成员,此时能识别到[ObservableProperty]生成的属性,所以序列化正常。 [property: JsonInclude]的作用是将特性修饰目标指向字段对应的自动生成属性,让Json源生成器将其纳入序列化范围。
内容的提问来源于stack exchange,提问作者Melon NG
相关产品推荐
相关产品推荐

