Question

I have a quite a complex string representing a json object. I need to convert this in to some form so that I can return it as a JsonResult in my MVC controller.

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

This string is built dynamically.

Not sure if I'm in the right track but I parsed this into "JObject" using NewtonSoft, but I also need to convert this string into a JsonResult type(which should be recognized as a Json object by Jquery)

Was it helpful?

Solution

Since you already have a string you don't need to return a JsonResult. The JsonResult basically converts an object into JSON.

You can just return it in a ContentResult and specify the correct content type:

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

Just give your Action method ActionResult as a return type and that should work

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top