2013-03-27 50 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