使用无效的枚举值序列化对象 [英] Serializing Object With Invalid Enum Value

查看:41
本文介绍了使用无效的枚举值序列化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Windows Phone 7 项目,该项目连接到 .NET Web 服务以按需获取数据.WP7 项目和 Web 服务都使用相同 c# 类库的副本.这个库的一部分是 EmployeeType 的枚举:

I have a Windows Phone 7 project that connects to a .NET web service to fetch data on demand. Both the WP7 project and the web service use a copy of the same c# class library. Part of this library is an enum of EmployeeType:

Public enum EmployeeType
{
    Standard = 0,
    TeamLeader = 105
}

自应用发布以来,Web 服务类库对其进行了更改 - 添加了新的枚举值.(高级经理 = 110)

Since the app was released, the web service class library has had a change made to it - adding a new enum value. (SeniorManager = 110)

因此,当我在手机上收到一个包含新枚举值的属性的对象时,我在尝试将其添加到隔离存储时收到 SerializationException.这是因为新的枚举值无法序列化,因为 WP7 类库没有对其进行相同的更新,并且枚举值不存在.

Therefore, when I receive an object on the phone with a property containing the new enum value, I get a SerializationException when attempting to add it to IsolatedStorage. This is because the new enum value cannot be serialized, as the WP7 class library has not had the same update made to it and the enum value does not exist.

我想要实现的是仍然能够序列化对象,但忽略无效的枚举值,或用有效的值替换(理想情况下<代码>标准= 0).

What I would like to achieve is to still be able to serialize the object, but ignore the invalid enum value, or replace it with a valid one (ideally Standard = 0).

这将使我能够处理对网络服务枚举所做的任何未来添加,而不会破坏应用程序的功能.

This will enable me to handle any future additions made to the web service enum, without breaking the functionality of the app.

注意事项:

  • 上面的枚举/值是为了问题的目的而设计的,而不是所讨论的实际枚举.
  • 值将被序列化为不正确的值这一事实对于应用而言并不重要.

谢谢!

推荐答案

我最终使用了 JSON.NET 反序列化来自服务器的数据(reader 是响应流的 StreamReader.TResponse 是服务器预期的通用响应.):

I ended up using JSON.NET to deserialize the data from the server (reader is a StreamReader for the response stream. TResponse is the generic response expected from the server.):

var serializer = new JsonSerializer();
serializer.Converters.Add(new JsonEnumTypeConverter());
this.Response = serializer.Deserialize<TResponse>(new JsonTextReader(reader));

JsonEnumTypeConverter 类检查从服务器返回的枚举值对于给定类型是否有效.如果不是,则默认为零.(总是出现在枚举上).该类定义如下:

The JsonEnumTypeConverter class checks that the enum value returned from the server is valid for the given type. If not, then it's defaulted to zero. (Always present on enums). This class is defined as follows:

private class JsonEnumTypeConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType.IsEnum;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        try
        {
            var value = Enum.Parse(objectType, reader.Value.ToString(), true);
            if (IsFlagDefined((Enum)value))
            {
                return value;
            }
            else
            {
                return 0;
            }
        }
        catch (Exception)
        {
            return 0;
        }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(value);
    }

    private static bool IsFlagDefined(Enum e)
    {
        decimal d;
        return (!decimal.TryParse(e.ToString(), out d));
    }
}

请注意,我使用自定义 IsFlagDefined 方法,而不是 Enum.IsDefined,因为我的枚举包含 Enum.IsDefined 的 [Flags] 属性不处理.(来源:Enum.IsDefined with flagged enums)

Note that I use the custom IsFlagDefined method, rather than Enum.IsDefined as my enums include [Flags] attributes which Enum.IsDefined does not handle. (Source: Enum.IsDefined with flagged enums)

另外,感谢 Darin Dimitrov这个问题 将我指向 JSON.NET 和 JsonConverter.

Also, credit to Darin Dimitrov's answer in this question for pointing me towards JSON.NET and the JsonConverter.

这篇关于使用无效的枚举值序列化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆