Gra*_*ntC 5 asp.net-mvc-4 asp.net-web-api
我试图从Web API更改json输出.假设我有像People这样的对象,当前的输出将是:
[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]
Run Code Online (Sandbox Code Playgroud)
但是我希望输出如下:
{"people":[{name:"John", sex:"M"},{name:"Simon", sex:"M"}]}
Run Code Online (Sandbox Code Playgroud)
关于如何做到这一点的任何想法?
Fil*_*p W 14
选项1 - 创建新模型
而不是返回
public IEnumerable<Person> Get()
Run Code Online (Sandbox Code Playgroud)
返回
public People Get()
Run Code Online (Sandbox Code Playgroud)
哪里
public class People {
public IEnumerable<Person> People {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
选项2 - 返回动态
而不是返回
public IEnumerable<Person> Get()
Run Code Online (Sandbox Code Playgroud)
返回
public dynamic Get() {
IEnumerable<Person> p = //initialize to something;
return new {people = p};
}
Run Code Online (Sandbox Code Playgroud)
选项3 - 修改JsonMediaTypeFormatter
你仍然可以回来
public IEnumerable<Person> Get()
Run Code Online (Sandbox Code Playgroud)
但添加以下类:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在在WebApiConfig中只注册新的格式化程序而不是旧的JSON格式化程序:
config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, new PeopleAwareMediaTypeFormatter());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2036 次 |
| 最近记录: |