简体   繁体   English

如何防止整个类被序列化?

[英]How to prevent an entire class from being serialized?

I am using Newtonsoft.Json to serialize a class and all of its members. 我正在使用Newtonsoft.Json来序列化一个类及其所有成员。 There is one particular class that many of its members are an instance of, I'd simply like to tell a class to not be serialized at all, so if any member that is an instance of that type is skipped. 有一个特定的类,它的许多成员是一个实例,我只想告诉一个类根本不被序列化,所以如果任何成员是该类型的实例被跳过。

Is this possible in C# by appending some sort of attribute to a class to mark it as non-serializable? 这是否可以在C#中通过将某种属性附加到类来将其标记为不可序列化?

I do not think this can be done using an attribute on the class. 我不认为这可以使用类上的属性来完成。 However you should be able to do it by implementing a custom JsonConverter which always serializes and deserializes any instance of this class to null . 但是,您应该能够通过实现自定义JsonConverter来实现,该自定义JsonConverter始终将此类的任何实例序列化和反序列化为null This code implements such behavior: 此代码实现了这样的行为:

class IgnoringConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteNull();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return null;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(ClassToIgnore);
    }
}

In this example, ClassToIgnore is the class you wish to ignore during serialization. 在此示例中, ClassToIgnore是您希望在序列化期间忽略的类。 Such classes should be decorated with the JsonConverter attribute: 这些类应该使用JsonConverter属性进行修饰:

[JsonConverter(typeof(IgnoringConverter))]
class ClassToIgnore

You can also register the converter as a default converter which is useful if you're using ASP.NET Web API. 您还可以将转换器注册为默认转换器 ,如果您使用的是ASP.NET Web API,则该转换器非常有用。

I have included a Console application sample to demonstrate the functionality: 我已经包含一个Console应用程序示例来演示功能:

using System;
using Newtonsoft.Json;

/// <summary>
/// Class we want to serialize.
/// </summary>
class ClassToSerialize
{
    public string MyString { get; set; } = "Hello, serializer!";

    public int MyInt { get; set; } = 9;

    /// <summary>
    /// This will be null after serializing or deserializing.
    /// </summary>
    public ClassToIgnore IgnoredMember { get; set; } = new ClassToIgnore();
}

/// <summary>
/// Ignore instances of this class.
/// </summary>
[JsonConverter(typeof(IgnoringConverter))]
class ClassToIgnore
{
    public string NonSerializedString { get; set; } = "This should not be serialized.";
}

class IgnoringConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteNull();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return null;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(ClassToIgnore);
    }
}

class Program
{
    static void Main(string[] args)
    {
        var obj = new ClassToSerialize();
        var json = JsonConvert.SerializeObject(obj);

        Console.WriteLine(json);

        obj = JsonConvert.DeserializeObject<ClassToSerialize>(json);

        // note that obj.IgnoredMember == null at this point

        Console.ReadKey();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM