1

If I have a string (which is already in JSON format) say

string JsonStr = "{ 'A': 123 }";

My API is

public JsonResult OnGetRetrieve()
{
    string JsonStr = "{ 'A': 123 }";
    return new JsonResult(JsonStr);  // This will return the Json as a string
}

If I wish to return as a Json object, I need to

return new JsonResult(JsonConvert.Deserialize(JsonStr));

I am sure there is a better way than this.

Thanks in advance.

3
  • Is it Minimal APIs or Controllers? Commented Jun 10, 2024 at 13:12
  • @GuruStron Minimal APIs Commented Jun 10, 2024 at 21:59
  • Have you checked the suggested answer does it work for you? Commented Jun 11, 2024 at 12:12

1 Answer 1

1

If you have a JSON string and you want to return it as JSON you can use Content helper methods. For example for minimal APIs with Results.Content (or TypedResults.Content):

return Results.Content(JsonStr); 

or in controllers:

return this.Content(JsonStr);

Possibly you will need to specify the contentType parameter (application/json).

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

Comments

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.