c# - 使用 JSON.NET 序列化对象时如何添加自定义根节点?

标签 c# json serialization json.net custom-attributes

我已经为我的一些对象添加了自定义属性,如下所示:

[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/

相关文章:

c# - 具有抽象保护成员的多线程?

c# - 如何从 C# 的 char * 到非托管 C++ DLL 传递和接收数据

c# - 如何在没有第三方库的情况下序列化对象+压缩然后解压+反序列化?

jquery - 从表元素而不是整个表单序列化

database - 将 Matlab 数组存储在 SQL Server varbinary 字段中

c# - 是否可以从通用列表设置图表数据源?

c# - 在 Travis CI 上使用 Mono 5.14.0.177、msbuild 15.0、nuget 4.7.1 构建失败,但在 VirtualBox 中无法重现

javascript - Json 编码 数组与仅转换为数组的对象的混合

json - 将json解析为qml中的listview

python - 做tostring()时丢失原始文本