IHttpActionResult与JSON字符串 [英] IHttpActionResult with JSON string

查看:569
本文介绍了IHttpActionResult与JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个最初返回HttpResponseMessage的方法,我想将其转换为返回IHttpActionResult.

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

我的问题是当前代码使用JSON.Net来序列化复杂的通用树结构,使用我编写的自定义JsonConverter效果很好(代码工作正常).

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

这是它返回的内容:

    string json = NodeToJson(personNode);

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

    return response;

NodeToJson方法是自定义转换器起作用的地方...

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

}

请注意,这将返回string,格式为JSON.

Note this returns a string, formatted as JSON.

如果我将其切换为IHttpActionResult,无论我尝试什么,它似乎都会失败.我可以保留它(它可以正常工作),但是我应该为此使用最佳实践,而IHttpActionResult似乎就是我应该使用的.

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.

我已经尝试过return Json(json);,但这会导致无效的,不可解析的JSON,大概是因为它正在尝试进行双重转换?

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);导致将JSON字符串包装为XML.

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

正确的方法是什么?

除此特定方法外,我现在已经成功转换了该项目中的每个方法,以使用IHttpActionResult.

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

这是将通用树序列化为JSON的过程.无论我尝试哪种方法,我都会获取无效的JSON. HttpResponseMsessage方法可以很好地工作,但是我无法通过IHttpActionResult返回有效的JSON.

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.

推荐答案

我遇到了同样的问题,并且这段代码对我有用(使用Newtonsoft.Json nuget包反序列化json):

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

似乎我们必须有一个对象才能使Json()正常工作.

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

这篇关于IHttpActionResult与JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆