枚举序列化的Json VS XML序列化、Json、XML、VS

2023-09-03 04:42:38 作者:自古空情多余恨

我已经在我的项目下的Enum

I have following Enum in my project

public enum CameraAccessMethod
{
    Manual = 0,
    Panasonic = 1,
    Axis = 2,
    AirCam = 3
}

我有一个对象序列化无论是JSON或XML根据不同的场景和对象的属性中的一个类型 CameraAccessMethod 的。我的问题是,当这个属性被序列化为XML,它会给字符串重新枚举值presentation(手动,松下,轴,Aircam),但在JSON是序列化到数值(0,1,2, 3)。如何避免这种不一致?我想在JSON序列化字符串为好。

I have an object that is serialized either to json or to XML depending upon different scenarios and one of object's property is of type CameraAccessMethod. The problem i have is that when this property is serialized to XML it will give string representation of enum values (Manual, Panasonic,Axis,Aircam) but in JSON it is serialized to number values (0,1,2,3). How can i avoid this inconsistency? i want strings in JSON serialization as well.

推荐答案

由于网络API RC您可以通过应用 StringEnumConvert 来获取字符串再枚举presentations在的Application_Start现有的 JsonMediaTypeFormatter 转换器集合()

Since Web API RC you can get string representations of enums by applying a StringEnumConvert to the existing JsonMediaTypeFormatter converter collection during Application_Start():

var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
var enumConverter = new Newtonsoft.Json.Converters.StringEnumConverter();
jsonFormatter.SerializerSettings.Converters.Add(enumConverter);
 
精彩推荐
图片推荐