我为我的一些对象添加了一个自定义属性,如下所示:
[JsonCustomRoot("status")]
public class StatusDTO
{
public int StatusId { get; set; }
public string Name { get; set; }
public DateTime Created { get; set; }
}
属性很简单:
public class JsonCustomRoot :Attribute
{
public string rootName { get; set; }
public JsonCustomRoot(string rootName)
{
this.rootName = rootName;
}
}
序列化对象实例时 JSON.NET 的默认输出如下:
{"StatusId":70,"Name":"Closed","Created":"2012-12-12T11:50:56.6207193Z"}
现在的问题是:如何使用自定义属性的值向 JSON 添加根节点,如下所示:
{status:{"StatusId":70,"Name":"Closed","Created":"2012-12-12T11:50:56.6207193Z"}}
我找到了几篇提到IContractResolver接口的文章,但我不知道该怎么做。我的尝试包括这段未完成的代码:
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
JsonObjectContract contract = base.CreateObjectContract(objectType);
var info = objectType.GetCustomAttributes()
.SingleOrDefault(t => (Type)t.TypeId==typeof(JsonCustomRoot));
if (info != null)
{
var myAttribute = (JsonCustomRoot)info;
// How can i add myAttribute.rootName to the root from here?
// Maybe some other method should be overrided instead?
}
return contract;
}