枚举序列化的Json VS XML [英] Enum Serialization Json vs XML

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

问题描述

我已经在我的项目下的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);

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

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