5

我正在尝试更改 Web API 的 json 输出。假设我有一个像 People 这样的对象,当前输出如下:

[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]

但是我希望输出如下:

{"people":[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]}

关于如何做到这一点的任何想法?

4

4 回答 4

14

选项 1 - 创建新模型

而不是返回

public IEnumerable<Person> Get()

返回

public People Get()

在哪里

public class People {
    public IEnumerable<Person> People {get; set;}
}

选项 2 - 返回动态

而不是返回

public IEnumerable<Person> Get()

返回

public dynamic Get() {
    IEnumerable<Person> p = //initialize to something;
    return new {people = p};
}

选项 3 - 修改 JsonMediaTypeFormatter

你仍然可以返回

public IEnumerable<Person> Get()

但添加以下类:

public class PeopleAwareJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
    public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, HttpContent content, TransportContext transportContext)
    {
        if ((typeof (IEnumerable<People>).IsAssignableFrom(type)))
        {
            value = new {people = value};
        }
        return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
    }
}

现在在 WebApiConfig 中只需注册新的格式化程序而不是旧的 JSON 格式:

config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, new PeopleAwareMediaTypeFormatter());
于 2013-01-22T04:40:01.143 回答
2

让我们假设列表对象的变量名是PersonList哪个返回

[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]

您可以简单地按以下方式返回而不会感到痛苦

       return new
        {
            people = PersonList
        };

那么你会有

{"people":[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]}
于 2014-10-05T01:13:24.323 回答
0

你一定有一个DTO为此JSON。所以,你所要做的就是为你的数组准备一个容器。

public class ReturnedJson
{
   public IList<People> People {get;set;}
}

 public class People
{
   public string name {get;set;}
   public string sex{get;set;}
}

这是我的假设,你有这个 json 的 DTO,因为你没有显示任何代码。

于 2013-01-22T04:41:04.697 回答
0

基于 Filip W 的第二个选项,这很好地从数据库中提取,因为 List 实现了 IEnumerable:

公共动态获取(){

List<Person> personList = new List<Person>();

using (DataTable dt = db.ExecuteDataTable("PeopleSelect")) {
    foreach (DataRow dr in dt.Rows) {
        personList.Add(new Person { name = (string)dr["name"], ...});
    }
}

return new { people = personList };

}

于 2014-01-26T22:45:53.643 回答