2009-07-24 65 views
4

我有一個類,目前繼承從詞典,然後添加一些第一類成員屬性。大致爲:JSON序列化與類繼承從字典<T,V>

public class Foo : Dictionary<string, string> 
{ 
    public string Bar { get; set; } 
    public string Baz { get; set; } 
} 

在然而此序列化對象的實例來JSON,看來串行只發射出我已經存儲了詞典中的關鍵字/值對。即使我將DataMember屬性應用於新的1st類屬性,JSON序列化程序似乎也不知道如何處理這些屬性,而只是忽略它們。

我假設有一些基本的基本知識,我錯過了,但通過代碼示例和文檔在.net的JSON序列化程序中搜索,我只發現了不符合我所做的簡單示例。我們從其他基類派生出來的所有其他類似乎都沒有表現出這個問題,它是從泛型字典中派生出來的,特別是給了我們適合的東西。

[編輯] 將字典移動到Foo作爲第一類屬性的缺點,是否有反正做這項工作?我假設掛斷是序列化程序不知道如何「命名」字典以區別於其他成員?

+0

可能的重複[如何將字典轉換爲C#中的JSON字符串?](http://stackoverflow.com/questions/5597349/how-do-i-convert-a-dictionary-toa-a- json-string-in-c) – 2014-03-07 16:39:42

回答

3

也許組成基地的解決辦法是在這種情況下更好:

using System; 
using System.Collections.Generic; 
using System.Runtime.Serialization.Json; 
using System.IO; 
using System.Text; 

class Program 
{ 
    static void Main() 
    { 
     Foo foo = new Foo { Bar = "bar", Baz = "baz" }; 
     foo.Items.Add("first", "first"); 

     DataContractJsonSerializer serializer 
      = new DataContractJsonSerializer(typeof(Foo)); 

     using (MemoryStream ms = new MemoryStream()) 
     { 
      serializer.WriteObject(ms, foo); 
      Console.WriteLine(Encoding.Default.GetString(ms.ToArray())); 
     } 
    } 
} 

public class Foo 
{ 
    public Dictionary<string, string> Items { get; set; } 
    public string Bar { get; set; } 
    public string Baz { get; set; } 

    public Foo() 
    { 
     this.Items = new Dictionary<string, string>(); 
    } 
} 

產生這樣的輸出:

{"Bar":"bar","Baz":"baz","Items":[{"Key":"first","Value":"first"}]}

這會幫助您解決問題的解決方法嗎?

+0

安德魯你打我打了,我正在編輯我的原始文件,因爲你張貼..我希望不必改變Foo類,因爲它是一個遺留件,並觸及一噸,但是如果我不能在電線上連續播放這個東西,我的手可能會被迫。 – bakasan 2009-07-24 20:10:25