【问题标题】:Expand dictionary to JSON fields将字典扩展到 JSON 字段
【发布时间】:2013-03-28 05:30:32
【问题描述】:

我们有这样的 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 对象字段。
  • 在反序列化过程中,传入 JSON 对象的所有不是 DTO 字段的字段都必须放入 Dictionary。

【问题讨论】:

    标签: c# json servicestack


    【解决方案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
        }      
    }
    

    【讨论】:

      猜你喜欢
      • 2015-02-13
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 2014-10-20
      • 1970-01-01
      • 1970-01-01
      • 2013-04-20
      • 2021-06-26
      相关资源
      最近更新 更多