IHttpActionResult with JSON string

倖福魔咒の 提交于 2019-12-06 04:22:25

问题


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.


回答1:


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.




回答2:


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



回答3:


Another recommendation is as below;

var json = JToken.FromObject(yourObject);
return Ok(json);



回答4:


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



回答5:


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.




回答6:


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



来源:https://stackoverflow.com/questions/36241098/ihttpactionresult-with-json-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!