QA:如何告诉NewtonSoft.Json.JsonConvert将枚举序列化为字符串而不是int

Q:
我目前有一个类(看起来像这样)

public class foo
{
 public MyEnumType Result { get; set; };
}

目前,当我这样做

foo a = new foo();
string str = JsonConvert.SerializeObject(a);

结果以int类型显示。有没有办法让我把它作为字符串类型?通过告诉它执行MyEnumTypeInstance.toString();

A:
JSON.Net有一个内置的转换器StringEnumConverter,您只需向要进行反序列化的属性添加
一个属性,例如:

[JsonConverter(typeof(StringEnumConverter))]
public MyEnumType Result { get; set; }

或在序列化期间指定转换器:

string str = JsonConvert.SerializeObject(a, new StringEnumConverter());

更多内容,参阅http://viadean.com

你可能感兴趣的:(问答)