我正在尝试更改 Web API 的 json 输出。假设我有一个像 People 这样的对象,当前的输出是这样的:
[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]
但是我希望输出是这样的:
{"people":[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]}
关于如何做到这一点的任何想法?
最佳答案
选项 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());
关于asp.net-mvc-4 - ASP.net Web API - 将数组名称添加到输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14451559/