The JsonResult class in ASP.NET Core MVC is your go-to tool when you need to return structured data in JSON (JavaScript Object Notation) format from your controller actions. JSON has become the de facto standard for data exchange in web APIs and modern web applications due to its simplicity, readability, and wide support across platforms and languages.
Creating a JsonResult Similar to ContentResult, you have a couple of convenient ways to create a JsonResult in your action methods: Instantiating JsonResult: return new JsonResult(person); Here, you pass the object (e.g., person) that you want to serialize into JSON directly to the JsonResult constructor.
Using the Json() Helper Method: return Json(person); The Json() method is a shorthand provided by the Controller base class, making it even easier to create a JsonResult.
Code // HomeController.cs [Route(“person”)] public JsonResult Person() { Person person = new Person() { Id = Guid.NewGuid(), FirstName = “James”, LastName = “Smith”, Age = 25 };
return Json(person); }
In this modified Person action: Person Object: A Person object is created with some sample data (including a unique ID). JSON Serialization: The Json(person) call serializes the person object into a JSON string. Response: The resulting JSON string is returned as a JsonResult, with the Content-Type header automatically set to application/json.
Output: The response sent to the client would look like this: { “id”: “123e4567-e89b-12d3-a456-426614174000”, “firstName”: “James”, “lastName”: “Smith”, “age”: 25 }