Web API返回转义的JSON [英] Web API returns escaped JSON

查看:393
本文介绍了Web API返回转义的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在.NET Core 2.0 Web API项目中有一个POST方法,该方法需要返回JSON(使用newtonsoft).方法结尾处有以下代码:

I have a POST method in a .NET core 2.0 web API project that needs to return a JSON (using newtonsoft). I have the following code at the end of the method:

ObjectResult objRes = new ObjectResult(JsonConvert.SerializeObject(result, settings));
objRes.ContentTypes.Add(new MediaTypeHeaderValue("application/json"));
return objRes

当我使用邮递员测试时,得到的结果如下:

When I test this using Postman I get a result like:

"{\"name\":\"test\",\"value\":\"test\"}"

如您所见,JSON仍在邮递员中转义.当我在.NET core 1.0项目中测试完全相同的代码时,在Postman中得到以下内容:

As you can see, the JSON is still escaped in postman. When I test the exact same code in a .NET core 1.0 project, I get the following in Postman:

{
  "name": "test",
  "value": "test"
}

如何在.NET Core 2.0项目中获得相同的结果? 我当时以为可能是由于Newtonsoft造成的,但是当我将反序列化调试为字符串时,调试器在.NET Core 1.0和2.0项目中显示的值完全相同(转义).

How can I get the same result in my .NET core 2.0 project? I was thinking it might have been due to Newtonsoft but when I debug the deserialization into a string, the debugger shows exactly the same (escaped) value in both the .NET core 1.0 and 2.0 project.

推荐答案

您只需在控制器中返回结果,它将由框架进行序列化.

You can just return result in the controller and it will be serialized by the framework.

[HttpPost]
public object Post()
{
    var result = new MyObject { Name = "test", Value = "test" };
    return result;
}

或者您可以这样做:

return new OkObjectResult(result);

或者,如果您从Controller继承:

Or if you inherit from Controller:

return Ok(result);

这篇关于Web API返回转义的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆