MVC controller manipulates the JSON
MVC controller manipulates the JSON
Here is my code:
[HttpGet]
[Produces("application/json")]
[Route("whatever")]
public ActionResult<JsonResult> Get()
string jsonText = ""city":"paris"";
return new JsonResult(JObject.Parse(jsonText));
This is the output I want:
"city":"paris"
This is the output I get:
"contentType":null,"serializerSettings":null,"statusCode":null,"value":"city":"paris"
How can I change my code to prevent .NET framework from wrapping my original JSON?
2 Answers
2
Then use a simpler and strongly typed result object instead of trying to manually create the JSON string.
[HttpGet]
[Produces("application/json")]
[Route("whatever")]
public IActionResult Get()
var model = new city = "paris" ;
return Ok(model);
the framework will serialize the model to the desired output
There is no problem with ASP.NET MVC's JsonResult, but you're using JSON.NET. In JSON.NET, when you convert an json string vi JObject.Parse(), it returns a JObject object that contains some members. If you want to get the converted json, you should use ToString(), as the following:
JsonResult
JObject.Parse()
JObject
ToString()
[HttpGet]
[Produces("application/json")]
[Route("whatever")]
public ActionResult<JsonResult> Get()
string jsonText = ""city":"paris"";
return new JsonResult(JObject.Parse(jsonText).ToString());
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Use Ok(your json object) instead of JsonResult
– Krazy_Tech
Aug 19 at 12:27