【问题标题】:Parsing a json formatted string into json and creating a jsonresult type object with c#将一个json格式的字符串解析成json并用c#创建一个jsonresult类型的对象
【发布时间】:2013-04-28 22:28:22
【问题描述】:

我有一个非常复杂的字符串来表示一个 json 对象。我需要将其转换为某种形式,以便可以在 MVC 控制器中将其作为 JsonResult 返回。

string result = "[
{
    ""TagGroupName"": ""group1"",
    ""Tags"": [
        {
            ""TagName"": ""G1tag1""
        },
        {
            ""TagName"": ""G1tag2""
        },
        {
            ""TagName"": ""G1tag3""
        }
    ]
},
{
    ""TagGroupName"": ""group2"",
    ""Tags"": [
        {
            ""TagName"": ""G2tag1""
        },
        {
            ""TagName"": ""G2tag2""
        }
    ]
}
]";

这个字符串是动态构建的。

不确定我是否在正确的轨道上,但我使用 NewtonSoft 将其解析为“JObject”,但我还需要将此字符串转换为 JsonResult 类型(Jquery 应将其识别为 Json 对象)

【问题讨论】:

  • 您可以使用内置的 JSON 解析器。它可能不是最快的解决方案,但应该可以。

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


【解决方案1】:

由于您已经有一个字符串,因此您不需要返回 JsonResult。 JsonResult 基本上将一个对象转换为 JSON。

您可以在 ContentResult 中返回它并指定正确的内容类型:

string result = @"[{ ""TagGroupName"": ""group1"", ""Tags"": [{""TagName"":""G1tag1""},{""TagName"":""G1tag2""},{""TagName"":""G1tag3""}]}, { ""TagGroupName"": ""group2"", ""Tags"": [{""TagName"":""G2tag1""},{""TagName"":""G2tag2""}]}]";

return new ContentResult { Content = result, ContentType = "application/json" };

只需将您的 Action 方法 ActionResult 作为返回类型就可以了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 2012-05-13
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多