asp net core mvc jsonresult example with code examples

ASP.NET Core MVC is a framework for building web applications and services. In this framework, JSON is the preferred format for data transfer between the client and the server.

JSONResult is an action result that returns a JSON formatted response. It is useful when you need to return a complex object to the client.

In this article, we will explore how to use JsonResult in ASP.NET Core MVC with examples.

Creating a new ASP.NET Core MVC project

Before we proceed, first, we need to create a new ASP.NET Core MVC project. Let's start by opening Visual Studio and creating a new project.

Select "ASP.NET Core Web Application" and click on the "Create" button.

In the next window, select "Web Application (Model-View-Controller)" and click on the "Create" button.

The new project will be created with the default template.

Now, let's add a new controller.

Adding a new controller

In the Solution Explorer, right-click on the Controllers folder and select "Add > Controller".

In the "Add Scaffold" dialog, select "MVC Controller with views, using Entity Framework" and click on the "Add" button.

In the next window, select the data context class and the model class, and click on the "Add" button.

The new controller will be created with the default actions.

Now, let's add a new action method that returns a JsonResult.

Returning a JsonResult

In the new controller, add a new action method as follows.

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace MvcJsonResult.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public JsonResult GetPerson()
        {
            var person = new { FirstName = "John", LastName = "Doe", Age = 30 };
            var json = JsonConvert.SerializeObject(person);
            return Json(json);
        }
    }
}

In the above code, we have added a new action method "GetPerson" that returns a JSON formatted response.

First, we have created a new person object with some values. Then, we have serialized the object using the Newtonsoft.Json library.

Finally, we have returned the JSON formatted string using the Json method of the controller.

Let's test the action method.

Testing the action method

To test the action method, run the project and navigate to the "https://localhost:5001/Home/GetPerson" URL.

The JSON formatted response will be displayed in the browser as follows.

"{\"FirstName\":\"John\",\"LastName\":\"Doe\",\"Age\":30}"

As we can see, the JsonResult has returned a JSON formatted response.

Now, let's improve the action method by returning a typed object instead of a string.

Returning a typed object

In the previous example, we have returned a JSON formatted string using the Json method of the controller. However, it is better to return a typed object instead of a string.

Let's modify the action method as follows.

using Microsoft.AspNetCore.Mvc;

namespace MvcJsonResult.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public JsonResult GetPerson()
        {
            var person = new { FirstName = "John", LastName = "Doe", Age = 30 };
            return Json(person);
        }
    }
}

In the above code, we have removed the serialization code and returned the person object directly using the Json method of the controller.

Let's test the action method again.

Testing the action method

To test the action method, run the project and navigate to the "https://localhost:5001/Home/GetPerson" URL.

The JSON formatted response will be displayed in the browser as follows.

{"FirstName":"John","LastName":"Doe","Age":30}

As we can see, the JsonResult has returned a typed object.

Conclusion

In this article, we have learned how to use JsonResult in ASP.NET Core MVC with examples. We have created a new ASP.NET Core MVC project, added a new controller, and returned a JSON formatted response using JsonResult. We have also learned how to return a typed object instead of a string.

JSON is a popular format for data transfer between the client and the server. JsonResult is a useful action result that simplifies the process of returning a JSON formatted response in ASP.NET Core MVC.

I hope you have found this article helpful. If you have any questions or comments, please feel free to leave them below.

let's discuss some more about the previous topics we covered.

Serializing and Deserializing JSON Data

In the previous example, we used the Newtonsoft.Json library to serialize an object into a JSON formatted string. We can also use it to deserialize a JSON string into an object.

Let's modify the previous example as follows.

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace MvcJsonResult.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public JsonResult GetPerson()
        {
            var json = "{\"FirstName\":\"John\",\"LastName\":\"Doe\",\"Age\":30}";
            var person = JsonConvert.DeserializeObject(json);
            return Json(person);
        }
    }
}

In the above code, we have created a JSON formatted string and deserialized it into an object using the JsonConvert.DeserializeObject method.

The returned JsonResult will contain the person object.

Testing the action method

To test the action method, run the project and navigate to the "https://localhost:5001/Home/GetPerson" URL.

The JSON formatted response will be displayed in the browser as follows.

{"FirstName":"John","LastName":"Doe","Age":30}

Application Programming Interface (API)

ASP.NET Core MVC can also be used to build APIs. In fact, ASP.NET Core is well-suited for building APIs.

Let's create a new API controller.

Creating a new API Controller

In the Solution Explorer, right-click on the Controllers folder and select "Add > Controller".

In the "Add Scaffold" dialog, select "API Controller with actions, using Entity Framework" and click on the "Add" button.

In the next window, select the data context class and the model class, and click on the "Add" button.

The new API controller will be created with the default actions.

Let's add a new action method that returns a JsonResult.

using Microsoft.AspNetCore.Mvc;

namespace MvcJsonResult.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PersonController : ControllerBase
    {
        [HttpGet]
        public ActionResult<object> GetPerson()
        {
            var person = new { FirstName = "John", LastName = "Doe", Age = 30 };
            return Ok(person);
        }
    }
}

In the above code, we have created a new API controller "PersonController" and added a new action method "GetPerson". We have also decorated the controller with the [ApiController] attribute and marked the action method with the [HttpGet] attribute.

The returned ActionResult will contain the person object.

Testing the action method

To test the action method, run the project and navigate to the "https://localhost:5001/api/Person" URL.

The JSON formatted response will be displayed in the browser as follows.

{"firstName":"John","lastName":"Doe","age":30}

As we can see, the returned JSON object contains lowercase property names. This is because ASP.NET Core Web API uses lowercase naming conventions by default.

Summary

In this article, we have explored JSONResult in ASP.NET Core MVC with code examples. We have also discussed how to serialize and deserialize JSON data and how to build an API using ASP.NET Core.

JSONResult is a powerful feature in ASP.NET Core that simplifies the process of returning JSON formatted data to the client. The Newtonsoft.Json library provides a simple way to work with JSON data.

ASP.NET Core Web API is a great option for building APIs due to its performance and flexibility.

I hope you found this article informative and helpful. If you have any questions or comments, please feel free to leave them below.

Popular questions

  1. What is JSONResult in ASP.NET Core MVC?
    Answer: JsonResult is an action result in ASP.NET Core MVC that returns data in JSON format.

  2. How do you return a JSON formatted response using JsonResult in ASP.NET Core MVC?
    Answer: You can return a JSON formatted response using the Json method of the controller. For example, return Json(person) will return a JSON formatted response containing the person object.

  3. How do you serialize an object into a JSON formatted string using the Newtonsoft.Json library?
    Answer: You can serialize an object into a JSON formatted string using the JsonConvert.SerializeObject method of the Newtonsoft.Json library. For example, var json = JsonConvert.SerializeObject(person) will serialize the person object into a JSON formatted string.

  4. How do you deserialize a JSON string into an object using the Newtonsoft.Json library?
    Answer: You can deserialize a JSON string into an object using the JsonConvert.DeserializeObject method of the Newtonsoft.Json library. For example, var person = JsonConvert.DeserializeObject(json) will deserialize the json string into a person object.

  5. Can you use ASP.NET Core MVC to build APIs?
    Answer: Yes, ASP.NET Core MVC can be used to build APIs. In fact, ASP.NET Core is well-suited for building APIs due to its performance and flexibility. You can use an API controller to build an API in ASP.NET Core MVC.

Tag

Examples

My passion for coding started with my very first program in Java. The feeling of manipulating code to produce a desired output ignited a deep love for using software to solve practical problems. For me, software engineering is like solving a puzzle, and I am fully engaged in the process. As a Senior Software Engineer at PayPal, I am dedicated to soaking up as much knowledge and experience as possible in order to perfect my craft. I am constantly seeking to improve my skills and to stay up-to-date with the latest trends and technologies in the field. I have experience working with a diverse range of programming languages, including Ruby on Rails, Java, Python, Spark, Scala, Javascript, and Typescript. Despite my broad experience, I know there is always more to learn, more problems to solve, and more to build. I am eagerly looking forward to the next challenge and am committed to using my skills to create impactful solutions.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top