JSONResult to String

C#Jsonasp.net Mvc-2Serialization

C# Problem Overview


I have a JsonResult that is working fine, and returning JSON from some POCO's. I want to save the JSON as a string in a DB.

public JsonResult GetJSON()
{
    JsonResult json = new JsonResult
    {
        Data = GetSomPocos()
    }; 
    return json;
}

I need to audit the response, so I want to save the json into a DB. I am having trouble finding a way to get the JSON as a string.

Any help is appreciated.

C# Solutions


Solution 1 - C#

You're looking for the JavaScriptSerializer class, which is used internally by JsonResult:

string json = new JavaScriptSerializer().Serialize(jsonResult.Data);

Solution 2 - C#

You can also use Json.NET.

return JsonConvert.SerializeObject(jsonResult.Data);

Solution 3 - C#

json = " { \"success\" : false, \"errors\": { \"text\" : \"绑定登录失败!\" } }";            
return new MemoryStream(Encoding.UTF8.GetBytes(json));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDustin LaineView Question on Stackoverflow
Solution 1 - C#SLaksView Answer on Stackoverflow
Solution 2 - C#PadmalochanView Answer on Stackoverflow
Solution 3 - C#user2129004View Answer on Stackoverflow