我已经为我的一些对象添加了自定义属性,如下所示:
[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;
}
最佳答案
如果您使用匿名对象怎么办?
JSON.Serialize(new { status = targetObject});
关于c# - 使用 JSON.NET 序列化对象时如何添加自定义根节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13839426/