IHttpActionResult with JSON string

╄→гoц情女王★ 提交于 2019-12-04 09:10:33
Felipe Torres

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.

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

Another recommendation is as below;

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

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

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.

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

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