c# - 如何在返回相同对象类型的列表时显示Json对象名称/标签

标签 c# .net json asp.net-web-api json.net

这是我的类(class)

[DataContract(Name="Test")]
public class Test
{
  [DataMember]
  public string Name { get; set; }    
  [DataMember]
  public string Type { get; set; }
}

[DataContract(Name="Root")]
public static class Root
{
   [DataMember(Name="TestList")]
   public static List<Test> TestList { get; set; }
}


Expected Json To be returned 
  {
   "Test":[
    {
    "Name": "MyApp",      
    "Type": "web"
    },
    {
    "Name": "MyDatabase",      
    "Type": "db"
    }
     ]
  }

Actual Json Returned 

 [
  {
    "Name": "MyApp",      
    "Type": "web"
  },
  {
    "Name": "MyDatabase",      
    "Type": "db"
  }
]

WebApi 方法返回对象

    [HttpGet]
    public IEnumerable<Test> Get()
    {
        return Root.TestList;
    }

我面临的问题是,当我运行上面的代码时,我看到以“实际”格式返回的 json 数据,但我希望看到“预期格式”的 Json(请参阅上面的格式) .
唯一的区别是数组的标签。我怎样才能贴上这个标签?
我查看了大量的 json 文档,但没有运气。请帮忙。

最佳答案

您的方法返回一个 List<Test>所以这将被序列化为一个 JSON 数组。如果您想查看具有命名数组值属性的 JSON 对象,则需要返回包含适当命名属性的 POCO,例如您的 Root :

[HttpGet]
public Root Get()
{
    return Root;
}

此外,您需要将名称从 TestList 更改为至 Test :

[DataContract(Name="Root")]
public class Root
{
   [DataMember(Name="Test")] // Changed this
   public List<Test> TestList { get; set; }
}

或者,如果您的 Root包含您不想序列化的其他属性,或者以其他方式无法序列化(因为它是静态的),您总是可以返回一些通用包装器,如下所示:

[DataContract]
public class RootWrapper<T>
{
    [DataMember(Name = "Test")]
    public T Test { get; set; }
}

然后

    [HttpGet]
    public RootWrapper<IEnumerable<Test>> Get()
    {
        return new RootWrapper<IEnumerable<Test>> { Test = Root.TestList };
    }

关于c# - 如何在返回相同对象类型的列表时显示Json对象名称/标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30036240/

相关文章:

json - JAX-RS/ Jersey : Change response body from Jackson JSON errors

.net - 如何使用 IntervalAutoMode.FixedCount

java - 无法在 Retrofit 2 中获取 json 对象和数组

c# - 返回一个字符串数组.net c# web api

c# - 从串口读取 100 行后,C# 中的 MySql 错误

c++ - 包装 C# C++

c# - 如何手动将数据添加到 dataGridView?

c# - 在 gridview 中,updatepanel 不工作

c# - 如何在依赖注入(inject)之外构造对象?

c# - 从 Task.Run 获取返回值