我有一個用作字典鍵的c#結構體。爲了使該字典轉換爲JSON我需要結構序列化爲字符串(就像json.net的內置結構)。JSON.Net將結構序列化/反序列化爲字符串
public struct CreditRating
{
public CreditRating(string json) : this()
{
var levels = json.Split(new[] { '~' }, StringSplitOptions.None);
if (levels.Count() >= 3) Level3 = levels[2];
if (levels.Count() >= 2) Level2 = levels[1];
if (levels.Any()) Level1 = levels[0];
}
public string Level1 { get; set; }
public string Level2 { get; set; }
public string Level3 { get; set; }
public override string ToString()
{
return string.Format("{0}~{1}~{2}", Level1, Level2, Level3);
}
public static CreditRating Parse(string json)
{
return new CreditRating(json);
}
}
而且我的測試:
var rating = new CreditRating { Level1 = "first", Level2 = "Sergey" };
var ratingJson = JsonConvert.SerializeObject(rating); // {"Level1":"first","Level2":"Sergey","Level3":null}
var rating2 = JsonConvert.DeserializeObject<CreditRating>(ratingJson);
var dict = new Dictionary<CreditRating, double> {{rating, 2d}};
var dictJson = JsonConvert.SerializeObject(dict); //{"first~Sergey~":2.0}
var failingTest = JsonConvert.DeserializeObject<Dictionary<CreditRating, double>>(dictJson);
的最後一條語句,因爲它不叫了我的解析方法或公共構造失敗。 我跟着文檔,但不能通過這個。
您應該不能正常使用'struct' ......除非你有特別的問題,你應該使用'class'。當你可以使用'Length'時儘量不要使用'Count()' – xanatos
結構總是有一個公共無參數的構造函數,這就是爲什麼Json.Net能夠完全反序列化結構的原因。你爲什麼期望解串器能夠調用你的方法,爲什麼你需要它們? 'Level'屬性應該已經被序列化了 –
請參見http://stackoverflow.com/a/7010231/613130 Json.NET和Dictionary鍵有侷限性 – xanatos