2013-03-27 90 views
2

我們有DTO類是這樣的:展開詞典JSON領域

public class DTO 
    { 
     public int Number { get; set; } 
     public string Title { get; set; } 

     public Dictionary<string, string> CustomFields { get; set; } 
    } 

我想序列/由ServiceStack以JSON其中CustomFields被擴展爲DTO領域反序列化的DTO。例如

new DTO 
{ 
    Number = 42 
    Title = "SuperPuper" 
    CustomFields = new Dictionary<string, string> {{"Description", "HelloWorld"}, {"Color", "Red"}} 
} 

連載到

{ 
    "Number":42, 
    "Title":"SuperPuper", 
    "Description":"HelloWorld", 
    "Color":"Red" 
} 

我怎樣才能做到這一點?

  • 在序列化過程中,所有字典字段必須表示爲JSON對象字段。
  • 在反序列化期間,不是DTO字段的傳入JSON對象的所有字段都必須置於Dictionary中。

回答

1

如果使用Newtonsoft庫,你可以這樣做:

DTO Test = new DTO 
    { 
     Number = 42, 
     Title = "SuperPuper", 
     CustomFields = new Dictionary<string, string> { { "Description", "HelloWorld" }, { "Color", "Red" } } 
    }; 

    String Json = Newtonsoft.Json.JsonConvert.SerializeObject(Test); 

    Json = Json.Replace("\"CustomFields\":{", ""); 
    Json = Json.Replace("}}", "}"); 

產生的JSON字符串看起來是這樣的:

{"Number":42,"Title":"SuperPuper","Description":"HelloWorld","Color":"Red"} 

[編輯]

我不是要做所有你的工作......這應該讓你開始:

// to reconstruct the object 
Newtonsoft.Json.Linq.JObject MyObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Json) as Newtonsoft.Json.Linq.JObject; 

// Create a new object here. 

foreach(var Token in MyObject) 
{   
    // sample 
    if (Token.Key == "Number") 
    { 
     // populate the fields of the new object with Token.Value 
    }  
} 
+0

那麼反序列化呢?將說明直接進入字典? – adt 2013-03-27 13:59:09

+0

不可以。您問過物體是否變平,現在變平了。 – 2013-03-27 15:10:23

+0

@SteveWellens:問題狀態_I要序列化/反序列化_ – starteleport 2013-03-27 16:00:12