将字典展开到JSON字段

时间:2013-03-27 13:31:46

标签: c# json servicestack

我们有这样的DTO课程:

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

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

我想通过ServiceStack将DTO序列化/反序列化为JSON,其中CustomFields作为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对象的所有字段都放入“字典”。

1 个答案:

答案 0 :(得分: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
    }      
}