0
在自定義類中,我有一個通用字典,它具有值類型的枚舉類型。請注意,枚舉類型不在我的控制之下(第三方程序集的一部分)。如何在泛型類中使用枚舉類型時將枚舉序列化爲字符串?
當我使用Newtonsoft序列化這樣的對象時,枚舉被寫爲整數。
如何將枚舉序列化爲字符串?
我已經嘗試在屬性上使用StringEnumConverter
,但它僅適用於屬性本身,而不適用於使用泛型。由於枚舉是在外部程序集中聲明的,因此我無法直接在枚舉上應用StringEnumConverter。
這裏是一個REPRO樣品:
輸出:
{"ExtendedData":{"First":0,"Second":1}}
代碼:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class Program
{
public static void Main()
{
var data = new Data();
data.ExtendedData.Add("First", Foo.Val1);
data.ExtendedData.Add("Second", Foo.Val2);
Console.WriteLine(JsonConvert.SerializeObject(data));
}
public class Data{
private readonly Dictionary<string, Foo> m_ExtendedData = new Dictionary<string, Foo>();
public Dictionary<string, Foo> ExtendedData {get { return m_ExtendedData ; }}
}
// !Actually from an external assembly
public enum Foo{
Val1,
Val2
}
}
@PatrickHofman,我不同意。關於更改字典功能的鏈接問題,關鍵要具體。這種情況只需要添加一個'JsonConverter',這幾乎不會太激烈。請參閱https://dotnetfiddle.net/c6JlZl – kiziu
對於您的問題,您可以編寫自定義JsonConverter。很好的例子,你可以在這裏看到:http://stackoverflow.com/questions/21908262/newtonsoft-json-deserializeobject-emtpy-guid-field – eocron
你可以使用: var json = JsonConvert.SerializeObject(data,new StringEnumConverter()) ; –