繁体   English   中英

如何序列化以[ScriptIgnore]属性修饰的属性?

[英]How to serialize a property which is decorated with the [ScriptIgnore] attribute?

我正在尝试使用[ScriptIgnore]属性序列化具有某些属性的对象。 但是,有时我希望JavaScriptSerializer 不要忽略具有该属性的属性。 尽管具有[ScriptIgnore]属性,仍然可以序列化整个对象吗?

这是一些示例代码:

public static string ConvertToJson(this object objectToConvert)
{
    var serializer = new JavaScriptSerializer();
    return serializer.Serialize(objectToConvert);
}

public static void ConvertFromJson(this object objectToConvert, string jsonString)
{
    var serializer = new JavaScriptSerializer();
    object dummy = serializer.Deserialize(jsonString, objectToConvert.GetType());

    foreach(PropertyInfo property in objectToConvert.GetType().GetProperties())
        if(property.CanRead && property.CanWrite && property.GetCustomAttribute<ScriptIgnoreAttribute>() == null)
            property.SetValue(objectToConvert, property.GetValue(dummy));
}

您可以通过编码和提供JavaScriptConverter对象来控制整个序列化过程。

为了进行测试,让我们使用带有ScriptIgnore属性修饰的单个属性的简单类:

public class TestObject
{
    [ScriptIgnore]
    public string TestString { get; set; }
}

...然后序列化它的一个实例:

var serializer = new JavaScriptSerializer();
Console.WriteLine(serializer.Serialize(new TestObject { TestString = "test" }));

该属性当然会被忽略。 输出:

{}

现在,我们将定义一个JavaScriptConverter 这里相关的部分是我们对Serialize()

public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
    var testObject = obj as TestObject;

    if (testObject != null)
    {
        // Create the representation. This is a simplified example.
        Dictionary<string, object> result = new Dictionary<string, object>();
        result.Add("TestString", testObject.TestString);        
        return result;
    }

    return new Dictionary<string, object>();
}

我们只需将被忽略的属性添加到输出中。 而已!

当您要序列化所有内容时,您将提供转换器。 并且在没有转换器的情况下,默认情况下,带注释的属性将被忽略。

用法:

serializer.RegisterConverters(new List<JavaScriptConverter> { new TestObjectConverter() });

输出:

{ “的TestString”: “测试”}


完整的代码转储:

void Main()
{
    var serializer = new JavaScriptSerializer();
    Console.WriteLine(serializer.Serialize(new TestObject { TestString = "test" })); // prints: {}
    serializer.RegisterConverters(new List<JavaScriptConverter> { new TestObjectConverter() });
    Console.WriteLine(serializer.Serialize(new TestObject { TestString = "test" })); // prints: {"TestString":"test"}
}

public class TestObject
{
    [ScriptIgnore]
    public string TestString { get; set; }
}

public class TestObjectConverter : JavaScriptConverter
{
    private static readonly IEnumerable<Type> supportedTypes = new List<Type> { typeof(TestObject) };

    public override IEnumerable<Type> SupportedTypes => supportedTypes;

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        var testObject = obj as TestObject;

        if (testObject != null)
        {
            // Create the representation. This is a simplified example. You can use reflection or hard code all properties to be written or do it any other way you like - up to you.
            Dictionary<string, object> result = new Dictionary<string, object>();
            result.Add("TestString", testObject.TestString);        
            return result;
        }

        return new Dictionary<string, object>();
    }
}

暂无
暂无

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

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