1

I want to send raw Json content in a string on ASP .Net Core controller output.

If I try to do it by returning the string itself double quotes in its content will be escaped and the client will not recognize it as a Json content but as a string. Eg. :

public async Task<ActionResult<MyClass>> Get()
{
    try
    {
        // here we build an object from a service with a complex dataset
        MyClass myObject = ...;  // business code here
        // serializing the object
        JsonSerializerOptions options = new()
        {
            WriteIndented = true,
            ReferenceHandler = ReferenceHandler.IgnoreCycles
        };

        string jsonDataset = JsonSerializer.Serialize<MyClass>(myObject , options);
        // or we could do simply for testing something like: jsonDataset = "{\"Id\"=10, \"Label\"=\"HelloWorld!\"}";
        // then we send it to the client
        return Ok(jsonDataset);
    } 
    catch (Exception ex)
    {
        return StatusCode(500, ex.Message);
    }
}

I cannot deserialize the json, it is too complex with object lists referencing other objects.

I cannot use NewtonSoft library, it is a no-go for my project's client. So no anonymous class for deserialization here :[|]

Is there a way to output the string "jsonObject" as an application/json content BUT WITHOUT double-quote escaping ?

Thanks for any help!

4
  • I think you just want to return Ok(myObject); Commented Oct 4, 2022 at 20:17
  • I'd use: public async Task<JsonResult> Get() ... then return new JsonResult(new {Data=YourModel})... Commented Oct 4, 2022 at 20:22
  • Thanks Robert, the Ok(myObject) was failing because of circular references in the object. Serialization needed option ReferenceHandler = ReferenceHandler.IgnoreCycles to work Commented Oct 4, 2022 at 20:31
  • 1
    Thanks pcalkins, it might work but with the option I mentionned in my previous comment may be :) Commented Oct 4, 2022 at 20:32

1 Answer 1

1

You can use the Content methods to return the string and specify the content type:

return Content(
  jsonDataset, 
  "application/json");
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Marcus, I finaliy found something by re-reading the IActionResult docs with the JsonResult. I finaly simply used: return Json(myObject, options); With the options ReferenceHandler = ReferenceHandler.IgnoreCycles serializing the object in controller output worked. Thanks again though :)
Marcus, your solution works too :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.