c# - ASP.NET MVC : return JObject as JsonResult

标签 c# asp.net-mvc json.net

我正在尝试返回一个 JObject 作为我的操作结果。我用过 Newtonsoft.JsonJsonNetResult用于将对象转换为 JsonResult。 对于普通对象,我使用此语法将对象序列化为 JsonResult:

return new JsonResult
{
    ContentType = "application/json",
    ContentEncoding = System.Text.Encoding.UTF8,
    Data = myResult,
    JsonRequestBehavior = JsonRequestBehavior.AllowGet
};

myResult 是所需对象的实例,但是如下所示对 JObject (Newtonsoft.Json.Linq.JObject) 尝试此操作会返回无效结果,即 [[[]]]:

JObject jsonObject = new JObject();
jsonObject["error"] = "invalid_id";
return new JsonResult
{
    ContentType = "application/json",
    ContentEncoding = System.Text.Encoding.UTF8,
    Data = jsonObject,
    JsonRequestBehavior = JsonRequestBehavior.AllowGet
};

在这种情况下如何序列化 JObject?

最佳答案

这对我有用!!

        var serialized = JsonConvert.SerializeObject(response, 
                 new JsonSerializerSettings() {
                     ContractResolver = new CamelCasePropertyNamesContractResolver() 
        });

        return new ContentResult()
        {
            Content = serialized,
            ContentType = "application/json",
        };

response 是一个包含 JObject 类型属性的 c# 类的实例。 这导致 Ok(response) 为 jobject 中的每个属性返回空数组符号 ([])。手动序列化并将其作为 contentresult 为我解决。

关于c# - ASP.NET MVC : return JObject as JsonResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42315429/

相关文章:

c# - MVC如何为大型结果集添加分页

c# - IEnumerable FirstOrEmpty 扩展

asp.net-mvc - ASP.NET MVC - WebSecurity 是如何工作的?

c# - 从 Unity 中的另一个脚本调用 IEnumerator 方法并获取其返回值

c# - 从 ASP.NET 网站 Webforms 调用 ASP.Net Web API

c# - 在 ASP.NET MVC 中设置默认的 JSON 序列化程序

c# - JSON 数据在反序列化期间未与 Dictionary 属性绑定(bind)

c# - 有没有办法让 Newtonsoft.Create 在界面上调用您的自定义创建方法?

c# - 验证纬度和经度

c# - AuthorizationFilterAttribute 的正确用法