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
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 ? 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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With