使用 JSON.NET 返回 ActionResult [英] Using JSON.NET to return ActionResult

查看:24
本文介绍了使用 JSON.NET 返回 ActionResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 C# 方法来序列化一个模型并返回一个 JSON 结果.这是我的代码:

I'm trying to write a C# method that will serialize a model and return a JSON result. Here's my code:

    public ActionResult Read([DataSourceRequest] DataSourceRequest request)
    {
        var items = db.Words.Take(1).ToList();
        JsonSerializerSettings jsSettings = new JsonSerializerSettings();
        jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        var converted = JsonConvert.SerializeObject(items, null, jsSettings);
        return Json(converted, JsonRequestBehavior.AllowGet);
    }

我在 Chrome 中转到 Words/Read 时得到以下 JSON 结果:

I got the following JSON result when I go to Words/Read in Chrome:

"[{"WordId":1,"Rank":1,"PartOfSpeech":"article","Image":"Upload/29/1/Capture1.PNG","FrequencyNumber":"22038615","Article":null,"ClarificationText":null,"WordName":"the | article","MasterId":0,"SoundFileUrl":"/UploadSound/7fd752a6-97ef-4a99-b324-a160295b8ac4/1/sixty_vocab_click_button.mp3","LangId":1,"CatId":null,"IsActive":false}

我认为 " 转义引号是您双重序列化对象时出现的问题.来自其他问题:WCF JSON 输出正在获取不需要的引号 &添加了反斜杠

I think the " escaped quotes are a problem that occurs when you double serialize an object. From other questions: WCF JSON output is getting unwanted quotes & backslashes added

看起来我对对象进行了双重序列化,因为我首先使用 JSON.NET 进行序列化,然后将结果传递给 Json() 函数.我需要手动序列化以避免引用循环,但我认为我的视图需要一个 ActionResult.

It definitely looks like I'm double serializing my object, since I first serialize using JSON.NET and then pass my result into the Json() function. I need to manually serialize to avoid referenceloops, but I think my View needs an ActionResult.

如何在此处返回 ActionResult?我是否需要,或者我可以只返回一个字符串?

How can I return an ActionResult here? Do I need to, or can I just return a string?

推荐答案

我发现了一个类似的 stackoverflow 问题:Json.Net 和 ActionResult

I found a similar stackoverflow question: Json.Net And ActionResult

那里的答案建议使用

return Content( converted, "application/json" );

这似乎适用于我非常简单的页面.

That seems to work on my very simple page.

这篇关于使用 JSON.NET 返回 ActionResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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