Skip to main content
 首页 » 编程设计

c#之如何防止使用 Newtonsoft JSON 序列化 DependencyObjects 上的 DependencyObjectType 信息

2024年02月05日11mfryf

当使用 Newtonsoft 的 JSON(版本 8.0.0)为 .Net/C# 序列化 DependencyObject 派生类时,我注意到它总是序列化DependencyObjectType 和 Dispatcher 对象以及我的所有派生类的属性。由于 DependencyObjectType 和 Dispatcher 对象来 self 继承自的 DependencyObject 类,我如何添加智能标记或属性(例如 [JsonIgnore]) 以防止它们被序列化?还是我的思考方式有误?

示例类代码:

public class MyClass : DependencyObject 
{ 
    public int MyProperty 
    { 
        get { return (int)GetValue(MyPropertyProperty); } 
        set { SetValue(MyPropertyProperty, value); } 
    } 
    public static readonly DependencyProperty MyPropertyProperty = 
        DependencyProperty.Register("MyProperty", typeof(int), typeof(ownerclass), new PropertyMetadata(0)); 
} 

序列化器代码:

JsonSerializer serializer = new JsonSerializer(); 
using (StreamWriter sw = new StreamWriter(filePath)) 
using (JsonWriter jw = new JsonTextWriter(sw)) 
{ 
    serializer.Serialize(jw, MyInstance); 
} 

当序列化时,我得到了这个巨大的 Blob (除了第一行之外的所有 Blob 都是不需要的):

{ 
    "MyProperty": 0, 
    "DependencyObjectType": { 
      "Id": 148, 
      "SystemType": "MyProject.MyClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", 
      "BaseType": { 
        "Id": 0, 
        "SystemType": "System.Windows.DependencyObject, WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=xxx", 
        "BaseType": null, 
        "Name": "DependencyObject" 
      }, 
      "Name": "MyClass" 
    }, 
    "IsSealed": false, 
    "Dispatcher": { 
      "Thread": { 
        "ManagedThreadId": 17, 
        "ExecutionContext": null, 
        "Priority": 2, 
        "IsAlive": true, 
        "IsThreadPoolThread": true, 
        "IsBackground": true, 
        "ThreadState": 4, 
        "ApartmentState": 1, 
        "CurrentUICulture": "en-US", 
        "CurrentCulture": "en-US", 
        "Name": null 
      }, 
      "HasShutdownStarted": false, 
      "HasShutdownFinished": false, 
      "Hooks": {} 
    } 
} 

请您参考如下方法:

您可以使用 OptIn 抑制类型层次结构中除必需属性之外的所有属性序列化的方法:

[JsonObject(MemberSerialization = MemberSerialization.OptIn)] 

并标记序列化属性:

[JsonProperty]