Skip to main content

Posts

Showing posts from August, 2014

MVC: Return JSON result in action

There are two ways to return JSON-formatted content to caller: 1. MVC framework provides the JsonResult class to send JSON-formatted content to the caller. Suppose you have a C# object and you would like to return this C# object as JSON string to caller, you can use Json() method.         [ HttpPost ]         public JsonResult ValidateUser( string Password)         {             if (Password == ConfigurationManager.AppSettings[ "AccessPassword" ])                 return Json( new { Valid = true });             else                 return Json( new { Valid = false });         } 2. If you have a valid JSON string at the backend and you would like to return it to front end, you can use ContentResult class to send JSON-formatted content to the caller.         public ContentResult CalculateResults()         {             return new ContentResult { Content = @ " { ""Year2014"": 100,  ""Year2015"": 200,  ""Year2016"

Convert Json string to C# object

There are several ways to convert Json string to c# object. I have used  JavaScriptSerializer and DataContractJsonSerializer. Both of them seem not good to handle complex Json object. Then I come across a new third-party Json converting library NewtonSoftJson.dll. It is included in MVC project. It seems very good to handle complex Json object. For example, I have an array of dictionary<int, double> type like this: string jsonString = "[ {204:5.00,205:5.5,206:5.32,207:5.50,208:5.70,209:5.92}, {204:5.50,205:5.66,206:5.83,207:6.02,208:6.23,209:6.45}, {204:6.00,205:6.6,206:6.34,207:6.53,208:6.75,209:6.98}, {204:6.50,205:6.67,206:6.85,207:7.05,208:7.27,209:7.5}, {204:7.00,205:7.7,206:7.36,207:7.57,208:7.80,209:8.04}, {204:7.50,205:7.68,206:7.87,207:8.08,208:8.32,209:8.58}, {204:8.00,205:8.8,206:8.38,207:8.60,208:8.84,209:9.}, {204:8.50,205:8.69,206:8.89,207:9.2,208:9.37,209:9.64}, {204:9.00,205:9.9,206:9.40,207:9.63,208:9.89,209:20.7}, {204:9.50,205:9.70,206:9.9,2