9

I have a method that originally returned an HttpResponseMessage and I'd like to convert this to return IHttpActionResult.

My problem is the current code is using JSON.Net to serialize a complex generic tree structure, which it does well using a custom JsonConverter I wrote (the code is working fine).

Here's what it returns:

    string json = NodeToJson(personNode);

    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StringContent(json, Encoding.UTF8, "application/json");

    return response;

The NodeToJson method is where the custom converter comes into play ...

private static string NodeToJson(Node<Person> personNode) {

    var settings = new JsonSerializerSettings {
        Converters = new List<JsonConverter> { new OrgChartConverter() },
        Formatting = Formatting.Indented
    };

    return JsonConvert.SerializeObject(personNode, settings);

}

Note this returns a string, formatted as JSON.

If I switch this to IHttpActionResult, it seems to fail regardless of what I try. I can just leave it (it works) but I am supposed to be using best practices for this and IHttpActionResult seems to be what I should be using.

I have tried to return Json(json); but this results in invalid, unparsable JSON, presumably because it's trying to do a double conversion?

return Ok(json); results in the JSON string being wrapped in XML.

What is the right way to do this?

EDIT:

I have successfully converted every method in this project to use IHttpActionResult now except this particular method.

It's a serialization of a generic tree to JSON. Regardless of what approach I try, I get back invalid JSON. The HttpResponseMsessage approach works fine, but I can not get valid JSON back with IHttpActionResult.

9 Answers 9

12

You can create your own IHttpActionResult class instance to return the JSON and a method in your controller or base controller class to utilize it.

Create the IHttpActionResult instance that sets the content and status code:

public class JsonTextActionResult : IHttpActionResult
{
    public HttpRequestMessage Request { get; }

    public string JsonText { get; }

    public JsonTextActionResult(HttpRequestMessage request, string jsonText)
    {
        Request = request;
        JsonText = jsonText;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(Execute());
    }

    public HttpResponseMessage Execute()
    {
        var response = this.Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new StringContent(JsonText, Encoding.UTF8, "application/json");

        return response;
    }
}

Add a method to your controller to create the result. Here is a Web API example:

public class MyApiController : ApiController
{
    protected internal virtual JsonTextActionResult JsonText(string jsonText)
    {
        return new JsonTextActionResult(Request, jsonText);
    }

    [HttpGet]
    public IHttpActionResult GetJson()
    {
        string json = GetSomeJsonText();
        return JsonText(json);
    }
}
7

Another recommendation is as below;

var json = JToken.FromObject(yourObject);
return Ok(json);
3
  • 1
    This solution worked best for me...even handles content type of response to set to "application/json" when request sent from Chrome (that usually accepts XML by default).
    – Jason W
    Commented Sep 13, 2018 at 12:21
  • This was by far the best for me too. I have added the following: var json = JToken.FromObject(yourObject, new JsonSerializer { ContractResolver = new CamelCasePropertyNamesContractResolver() });
    – w0ns88
    Commented Apr 15, 2019 at 11:24
  • only solution that worked for me. this uses the Newtonsoft.Json.Linq package.
    – Axelle
    Commented Feb 3, 2021 at 16:30
3

Some of the solutions here are converting string to JSON, that's not necessary. You are just using computer resources for nothing.

// Instead of 
//    return Ok(jsonstring);
// do:
      HttpResponseMessage response = this.Request.CreateResponse(HttpStatusCode.OK);
      response.Content = new StringContent(jsonstring, Encoding.UTF8, "application/json");
      Request.RegisterForDispose(response); //To avoid the Pragma CA2000 warning
      return ResponseMessage(response);

Another solution At client side

You can make a small change to be prepared to receive a string and convert it if necessary. The code bellow is Javascript

    var data;
    if (typeof weapiresponse == "string")
        data = JSON.parse(weapiresponse);
    else
        data = weapiresponse;
2

I've got the same problem and this piece of code worked for me (Using Newtonsoft.Json nuget package to deserialize the json):

var unserializedContent = JsonConvert.DeserializeObject(json);
return Json(unserializedContent);

It seems we must have an object in order to Json() work as it should.

1
  • 4
    You are deserializing the json string and serializing again before sending.This will impact the performance and scalability of the application. \ Commented Aug 9, 2017 at 5:10
1

If you have no intention of using XML as a return type, you can also remove the XmlFormatter in your WebApiConfig:

config.Formatters.Remove(config.Formatters.XmlFormatter);
4
  • I added this and it did not help. I am still getting unparsable JSON back. I have a Chrome extension to make JSON "pretty" and this formatter can no longer work with the results of this. It does work with my original code. This is with return Ok(json); in place. I will note that it DID remove the XML wrappings. I guess I will run this through Fiddler and see what the headers are.
    – Patrick
    Commented Mar 26, 2016 at 21:45
  • 1
    Whenever I have had to manually construct json to return, I've used the HttpResponseMessage return type, per your other SO post. Ok() seems to only serialize correctly when you pass it a class object and let the webapi do the serialization itself. Commented Mar 26, 2016 at 22:10
  • Yes, that's exactly what I'm seeing. This is a generic tree object consisting of some Node objects that are fairly complex: public class Node<T> : IEqualityComparer, IEnumerable<T>, IEnumerable<Node<T>> I've gone back to the HttpResponseMessage with my custom converter. I edited my question to say this. My other methods that were returning much simpler JSON converted to IHttpActionResult easily.
    – Patrick
    Commented Mar 26, 2016 at 22:12
  • 1
    Yes, I had the same issue when I need custom json returned for a JsTree page widget. I couldn't build the tree as a class object model. Commented Mar 26, 2016 at 22:14
0

The correct way is to return: Ok(json);

It's converting the result to XML because that's the default accepted return type. Try adding: Accept: application/json into your API request headers, I think that should resolve the issue.

1
  • What does this involve in terms of the Accept? Does this get into RegisterGlobalFilters? I don't want to make this 5 times more complex just to change the return type. I was hoping it would be easier, I already have proper JSON in a string, ready to send.
    – Patrick
    Commented Mar 26, 2016 at 21:48
0

I had the same problem with web-service returning JSON string in a XML-tag. I tried all the simple solutions Like :

return Json(text) , json deserialize and adding config.Formatter for json, but that did't help. I got double cotes around the json object or it was malformed.

Only the solution written by TGRA worked for me.

create your own IHttpActionResult class instance to return the JSON

0

For me, the only way to return an IHttpActionResult with the string content as Json in the following.

[HttpGet]
public IHttpActionResult ReturnStringAsJson()
{
    return this.ResponseMessage(new HttpResponseMessage
    {
        Content = new StringContent("[json string]"), 
        Encoding.UTF8, 
        "application/json"), 
    });
}
0

This is a very simple way for IActionResult that uses almost no resources:

    public async Task<IActionResult> WantJson()
    {
        var jsonString = JsonSerializer.Serialize(GetYourObjectHere());
        return Content(jsonString, "application/json");
    }

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.