简体   繁体   English

使用Json.NET将多个类的对象序列化为单个JSON

[英]Serialize object of multiple classes into a single JSON using Json.NET

I want to join objects of several classes together into a single JSON response, using Json.NET. 我想使用Json.NET将几个类的对象连接成一个JSON响应。 I want to build the following into a single JSON response: 我想将以下内容构建到单个JSON响应中:

{
  "data": [
    {
      "from": {
        "name": "Pawan Shrestha",
        "id": "100001187416487"
      },
      "created_time": "2012-04-22T10:21:22+0000",
      "unread": true,
      "to": {
        "name": "Shashwat Tripathi",
        "id": "100000559654730"
      }
    }
  ],
  "summary": {
    "unread_count": 1,
    "total_count": 1,
    "updated_time": "2012-04-22T10:21:22+0000"
  }
  "response_generated_on" : "2012-04-12 14:23:33"
}

I am creating JSON responses in the following way: 我正在以下列方式创建JSON响应:

Customer cs = new Customer(2011); //2011 is Customer A/c No.
string j = JsonConvert.SerializeObject(cs);

You can use anonymous types: 您可以使用匿名类型:

JsonConvert.SerializeObject(new {
    data = new[] { ... },
    summary = ...
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM