5

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\"}" 

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" } 

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.

2

2 Answers 2

7

I don't think you have to serialize your object before sending it. In .NET Core it will be serialized for you by default.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, however JSON.NET does have a couple of advantages over the .NET serializer, so see the solution stackoverflow.com/a/48335234/1317161 to make it work with JSON.NET
5

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; } 

Or you can do:

return new OkObjectResult(result); 

Or if you inherit from Controller:

return Ok(result); 

1 Comment

Yes, however JSON.NET does have a couple of advantages over the .NET serializer, so see the solution stackoverflow.com/a/48335234/1317161 to make it work with JSON.NET

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.