0

I'm trying to send data as plain Json, from my controller to the client side of my MVC application. The data is initially collected as a list of objects but I'm having trouble converting it to straight Json. Right now the code in my controller is as follows:

[HttpGet]
public JsonResult SecurityPermissionsTableData()
{
    List<SecurityPermissionsGridModel> list = securityPermissionsTable.Get(System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\').Last());

    string json = JsonConvert.SerializeObject(new
    {
        data = list
    });

    return ResultJson(json);
}

public JsonResult ResultJson(object data)
{
    return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = data };
}

When I use the JsonConvert.SerializeObject() function, it returns a string:

"{\"data\":[{\"Username\":\"loganfg\",\"readbutton\":null,\"editbutton\":null,\"deletebutton\":null}]}"

However I need to return plain Json in the form of:

{"data":[{"Username":"lgilmore","readbutton":"<a onclick='SP_read(\"7\")' class='SRKbutton tiny SP_rbutton'>Details</a>","editbutton":null,"deletebutton":null}]}

How can I convert the string the serialize function returns to plain Json? Or how do I alter my ResultJson() function to properly handle and convert the string?

2 Answers 2

5

JsonResult already serializes the object for you.
Therefore, it's serializing your string to a JSON string literal.

You should get rid of all of your code and just

return Json(list, JsonRequestBehaviour.AllowGet);
Sign up to request clarification or add additional context in comments.

Comments

2

You may simply use the Json method.

Pass the object you want to convert to json as the parameter.

public JsonResult SecurityPermissionsTableData()
{
   var permissionList = securityPermissionsTable
                .Get(System.Security.Principal.WindowsIdentity.GetCurrent()
                .Name.Split('\\').Last());
   return Json(permissionList , JsonRequestBehaviour.AllowGet);
}

3 Comments

Doesn't Json take an object, not a list of objects? And my code is: List<SecurityPermissionsGridModel> list not var list
I should've been more clear, I need it in the format of a Json array, not a Json object
@Life761 It will return an array if securityPermissionsTable.Get method returns a collection. If you pass a single object, It will return json for a single structure. If you pass an array, it will return an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.