Json.NET 使用根名称序列化对象 [英] Json.NET serialize object with root name

查看:37
本文介绍了Json.NET 使用根名称序列化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网络应用程序中,我使用的是 Newtonsoft.Json 并且我有以下对象

In my web app I'm using Newtonsoft.Json and I have following object

[Newtonsoft.Json.JsonObject(Title = "MyCar")]
public class Car
{
    [Newtonsoft.Json.JsonProperty(PropertyName = "name")]
    public string Name{get;set;}

    [Newtonsoft.Json.JsonProperty(PropertyName = "owner")]
    public string Owner{get;set;}
}

我想用根名称(类名)序列化它们.这是使用

and I want serialize them with root name (class name). This is desired format using

{'MyCar':
 {
   'name': 'Ford',
   'owner': 'John Smith'
 }
}

我知道我可以使用匿名对象来做到这一点,但是 Newtonsoft.Json 库中有任何属性或其他方式吗?

I know that I can do that with anonymous object, but is any property or another way in Newtonsoft.Json library?

推荐答案

使用匿名类

使用匿名类以您想要的方式塑造您的模型:

Use anonymous class

Shape your model the way you want using anonymous classes:

var root = new 
{ 
    car = new 
    { 
        name = "Ford", 
        owner = "Henry"
    }
};

string json = JsonConvert.SerializeObject(root);

这篇关于Json.NET 使用根名称序列化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆