Return 数据,格式为 Json,带有对象名称

Return data in Json format with object name

为 Web API 2 写了一个简单的函数,其中 returns 国家列表。它 returns 有效的 Json 格式但没有 array/object 名称。我有点难以理解这是如何实现的?

这是我的 C# 代码:

[Route("Constants/CountryList")]
[HttpGet]
public IHttpActionResult GetCountryList()
{
    IEnumerable<ISimpleListEntity> list = new CountryStore().SimpleSortedListByName();
    if (list == null || !list.Any())
    {
        return NotFound();
    }

    return Ok(list);
}

ISimpleListEntity接口代码在这里

public interface ISimpleListEntity
{
    int Id { get; set; }
    string Name { get; set; }
}

此服务 returns 以下 Json 输出 (没有 object/array 名称):

[  
   {  
      "Id":1,
      "Name":"[Select]"
   },
   {  
      "Id":4,
      "Name":"India"
   },
   {  
      "Id":3,
      "Name":"Singapore"
   },
   {  
      "Id":2,
      "Name":"United Arab Emirates"
   }
]

但是,我正在努力实现以下 Json 格式 (使用 object/array 名称 'CountryList'):

{  
   "CountryList":[  
      {  
         "Id":1,
         "Name":"[Select]"
      },
      {  
         "Id":4,
         "Name":"India"
      },
      {  
         "Id":3,
         "Name":"Singapore"
      },
      {  
         "Id":2,
         "Name":"United Arab Emirates"
      }
   ]
}

那是因为你正在序列化一个列表

你可以创建一个 dto,其中包含 属性 和你想要的名称并序列化它而不是列表

public class MyDto
{
      public List<ISimpleListEntity> CountryList {get;Set;}
}

您可以根据 Boas 的回答为此创建一个特定的 class,或者只使用匿名类型:

return Ok(new { CountryList = list });

基本上,无论哪种方式,您都需要一个具有适当 属性 的对象。如果你想稍后反序列化它并保持编译时检查,那么创建一个 class 是值得的 - 但如果你使用动态类型或者消费者无论如何都不会是 C# 代码,那么一个匿名类型会更简单。

您可以简单地使用匿名类型:

return Ok(new {
    CountryList = list
});

如果您也想 return 对象名称,那么最好 return 包含该列表的模型。

class Model
{
    IEnumerable<ISimpleListEntity> CountryList { get; set; };
}

然后在你的控制器中

return Ok(new model() {CountryList= ... });