如何获得JSON响应而不是XML? [英] How can I get a JSON response instead of XML?
本文介绍了如何获得JSON响应而不是XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是创建一个新的WebApi项目并保留默认控制器:
I just create a new WebApi project and keep the default controller :
public class ValuesController : ApiController
{
// GET api/values/5
public string Get(int id)
{
return "value";
}
//other services...
}
当我尝试请求它时,我无法获得有效的JSON结果.
When I try to request it, I can't get a valid JSON result.
- 没有特定的标头=>
application/xml
结果 - 具有
content-type
的标头分配给application/json
=>application/xml
结果 - 已将
accept
分配给application/json
的标头为我提供了正确的响应content-type
,但格式不正确的JSON:"value"
.
- No specific header =>
application/xml
result - Header with
content-type
assigned toapplication/json
=>application/xml
result - Header with
accept
assigned toapplication/json
gives me a correct responsecontent-type
but a malformed JSON :"value"
.
如何获取有效的JSON结果?
What is the way to get a valid JSON result ?
推荐答案
You will have to use JsonResult
as your return type:
public class ValuesController : ApiController
{
// GET api/values/5
public JsonResult Get(int id)
{
object returnObject;
// do here what you need to get the good object inside returnObject
return this.Json(returnObject, JsonRequestBehavior.AllowGet);
}
// other services...
}
这篇关于如何获得JSON响应而不是XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文