我们有这样的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"
}
我怎样才能做到这一点?
答案 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
}
}