You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JsonConvert序列化带ObservableProperty的类时重复字段如何解决

解决Newtonsoft.Json序列化ObservableProperty源生成属性重复问题

问题场景

使用Newtonsoft.Json序列化基于CommunityToolkit.Mvvm的ObservableObject派生类时,序列化结果同时包含了标记[JsonProperty]的原始字段和源生成的属性(如Id、Title),导致JSON出现重复键值对,不符合预期。

示例代码:

using Newtonsoft.Json;
using CommunityToolkit.Mvvm.ComponentModel;

public partial class Serie : ObservableObject
{
    [JsonProperty("id")]
    [ObservableProperty]
    long id;

    [JsonProperty("series")]
    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(SeriesAndSubSeries))]
    string title;
    
    [JsonProperty("sub_series")]
    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(SeriesAndSubSeries))]
    string subSerie;
}

错误序列化结果:

{"id":702,"series":"Androïden","sub_series":"","Id":702,"Title":"Androïden","SubSerie":""}

预期结果:

{"id":702,"series":"Androïden","sub_series":""}

解决方案

方法一:通过ObservableProperty参数自动添加JsonIgnore

CommunityToolkit.Mvvm支持在[ObservableProperty]特性中指定JsonIgnore = true,让源生成的属性自动带上[JsonIgnore]标记,避免被Newtonsoft.Json序列化:

修改后的代码:

using Newtonsoft.Json;
using CommunityToolkit.Mvvm.ComponentModel;

public partial class Serie : ObservableObject
{
    [JsonProperty("id")]
    [ObservableProperty(JsonIgnore = true)]
    long id;

    [JsonProperty("series")]
    [ObservableProperty(JsonIgnore = true)]
    [NotifyPropertyChangedFor(nameof(SeriesAndSubSeries))]
    string title;
    
    [JsonProperty("sub_series")]
    [ObservableProperty(JsonIgnore = true)]
    [NotifyPropertyChangedFor(nameof(SeriesAndSubSeries))]
    string subSerie;
}

这种方式直接修改特性参数即可,无需额外配置。

方法二:使用JsonObject特性限定序列化范围

在类上添加[JsonObject(MemberSerialization.OptIn)],指定仅序列化标记了[JsonProperty]的成员:

using Newtonsoft.Json;
using CommunityToolkit.Mvvm.ComponentModel;

[JsonObject(MemberSerialization.OptIn)]
public partial class Serie : ObservableObject
{
    [JsonProperty("id")]
    [ObservableProperty]
    long id;

    [JsonProperty("series")]
    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(SeriesAndSubSeries))]
    string title;
    
    [JsonProperty("sub_series")]
    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(SeriesAndSubSeries))]
    string subSerie;
}

此方式会强制序列化器仅处理显式标记的成员,未标记的源生成属性会被自动忽略。

内容的提问来源于stack exchange,提问作者Michel van den Heijkant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 13:35:17