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

时间:2015-05-04 17:30:31

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

这是我的班级

[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 docs,但没有运气。请帮忙。

1 个答案:

答案 0 :(得分:1)

您的方法返回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 };
    }