Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON string to JsonResult in MVC

We are trying to make mock service to serve JSON. We have plain JSON strings stored in static files and want to serve them to client as they are, without any additional wrappers. E.g. we have json string {"result_code":200,{"name":"John", "lastName": "Doe"}} and we want to get json response on client just like this without any Content or Data wrappers.

We have solution where we use data contracts and deserialize json to C# objects, but that's a bit complicated and we don't need it.

Thank you

like image 958
ekljuchanin Avatar asked Mar 27 '14 15:03

ekljuchanin


People also ask

How do I return JSON from action method?

To return data in a specific format from a controller that inherits from the Controller base class, use the built-in helper method Json to return JSON and Content for plain text. Your action method should return either the specific result type (for instance, JsonResult ) or IActionResult .

What is JsonResult type in MVC?

What is JsonResult ? JsonResult is one of the type of MVC action result type which returns the data back to the view or the browser in the form of JSON (JavaScript Object notation format).

How pass JSON data in MVC?

1) Create an attribute that overrides the OnActionExecuting event handler. 3) use attribute parameters to figure out the type of object you want to stream the data into. 4) deserialize the JSON object into your object.


Video Answer


1 Answers

You can do this by referencing System.Web.Mvc. Example in a quick console app I threw together:

using System;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace Sandbox
{
    class Program
    {
        private static void Main(string[] args)
        {
            //Added "person" to the JSON so it would deserialize
            var testData = "{\"result_code\":200, \"person\":{\"name\":\"John\", \"lastName\": \"Doe\"}}";

            var result = new JsonResult
            {
                Data = JsonConvert.DeserializeObject(testData)
            };

            Console.WriteLine(result.Data);
            Console.ReadKey();
        }

    }
}

You can just return the JsonResult from the mock method.

like image 82
Bill Avatar answered Sep 17 '22 14:09

Bill