Receiving Json data from ASP.NET CORE 2.1 using JsonResult

Code snippet for a ASP.NET Core 2.0 controller:

[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class GraficResourcesApiController : ControllerBase
{    
    private readonly ApplicationDbContext _context;

    public GraficResourcesApiController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public JsonResult GetGrafic(int ResourceId)
    {
        var scheduling = new List<Sheduling>();

        var events = from e in _context.Grafic.Where(c=>c.ResourceId == ResourceId)
                     select new
                     {
                         id = e.Id,
                         title = e.Personals.Name,
                         start = e.DateStart,
                         end = e.DateStop,
                         color = e.Personals.Color,
                         personalId = e.PersonalId,
                         description = e.ClientName
                     };
        var rows = events.ToArray();

        return Json(rows);
    }
}

Updating to ASP.NET Core 2.1

return Json (rows);

An error may arise stating that 'Json' does not exist in the current context. Removing 'Json' and simply returning

return rows;

This results in an error indicating inability to explicitly convert the type List () to JsonResult

How can we properly convert to Json in this scenario?

Answer №1

In , the ControllerBase does not include a built-in Json(Object) method. However, this functionality is present in the Controller class.

Therefore, you have two options: either modify the current controller to inherit from Controller

public class GraficResourcesApiController : Controller {
    //...
}

to utilize the Controller.Json Method, or manually create a new instance of JsonResult within the action

return new JsonResult(rows);

which essentially replicates what the method does internally in the Controller class

/// <summary>
/// Generates a <see cref="JsonResult"/> object that converts the specified <paramref name="data"/> object
/// to JSON format.
/// </summary>
/// <param name="data">The object to convert.</param>
/// <returns>The generated <see cref="JsonResult"/> that transforms the specified <paramref name="data"/>
/// into JSON for the response.</returns>
[NonAction]
public virtual JsonResult Json(object data)
{
    return new JsonResult(data);
}

/// <summary>
/// Generates a <see cref="JsonResult"/> object that converts the specified <paramref name="data"/> object
/// to JSON format.
/// </summary>
/// <param name="data">The object to convert.</param>
/// <param name="serializerSettings">The <see cref="JsonSerializerSettings"/> used by
/// the formatter.</param>
/// <returns>The generated <see cref="JsonResult"/> that transforms the specified <paramref name="data"/>
/// into JSON for the response.</returns>
/// <remarks>Users should store an instance of <see cref="JsonSerializerSettings"/> to prevent
/// restructuring cached data with each call.</remarks>
[NonAction]
public virtual JsonResult Json(object data, JsonSerializerSettings serializerSettings)
{
    if (serializerSettings == null)
    {
        throw new ArgumentNullException(nameof(serializerSettings));
    }

    return new JsonResult(data, serializerSettings);
}

Source

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to display JSON object on the screen

My current code is a snippet from my Asynctask that retrieves JSON data from a URL, parses it, and displays the information in TextViews on the screen. I suspect that the problem lies within the onPostExecute section where I am trying to pass the JSON info ...

Decoding whole numbers using JsonCpp

Currently, I am utilizing JsonCpp version 1.6.5 for the parsing of a JSON file that includes the following content: { "some-property" : 32 } Upon parsing, it appears that the type of the value is recognized as intValue instead of uintValue. I am curious ...

Ways to conceal a div element when the JSON data does not contain a value

If the value in "desc" is empty, then hide <div24> and <popup-desc>. html <div class="popup"> <div class="popup-top" style="background-color: '+e.features[0].properties.fill+';"> ...

When trying to URLEncode my JSON cookie, I encountered the error "Invalid JSON primitive" while attempting to stringify it

My website uses a cookie with a JSON object as its value. I serialize this to a specific type in my server code and back to JSON when passing it back as a cookie. Everything is working fine, but now I need to write to the cookie using JavaScript. The issu ...

Extracting a subclass from an array

Currently, I am delving into the world of coding as part of a project I'm working on. Here is an excerpt from my JavaScript code that interacts with Google Maps API: for (i = 0; i < results.length; i++) { console.log("Formatted Address: "+ re ...

The process of Ajax sending a sophisticated and extensive object to a Web API controller is frustratingly sluggish

Lately, I have been experiencing slow performance while trying to send a large object with a slightly complex structure using jQuery ajax to a Web API controller. It seems to take more than an hour for the request to reach the Web API controller method. h ...

Transforming Data into JSON: Learn how to dynamically adjust output mappings through serialization and normalization techniques

My controller's action is as follows: public function messagesAction() { $encoders = array(new JsonEncoder()); $normalizers = array(new GetSetMethodNormalizer()); $serializer = new Serializer($normalizers, $encoders); $message = $t ...

Converting Laravel Custom Error Validation JSON Response to an Array

I am currently working on developing an API for a registration form and running into an issue with the error format. While the validator correctly displays errors in an object format, I require the JSON response in an array format. $validator = Validato ...

A guide on how to Serialize LocalDate with Gson

I am working with a POJO that looks like this: public class Round { private ObjectId _id; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") @JsonDeserialize(using = LocalDateDeserializer.class) @JsonSerialize(using = L ...

I would like to know the best way to compare two JSON data sets, filter out any matching data, and then store the remaining results

To efficiently extract all Post Titles from a JSON API, I am utilizing another JSON API of users to further retrieve the count of comments for each Post. Here are the APIs being used: API for USERS: http://jsonplaceholder.typicode.com/users API for POSTS ...

Unable to correlate the response with the designated object

I'm currently facing an issue while attempting to utilize Angular4 HttpClient with an observable object that I've defined. My challenge lies in mapping the response to the designated object. The root of the problem appears to be related to my us ...

Transform GEOSwift.JSON into a Swift struct

In my GEOSwift implementation, I have a feature structured like this: { "type" : "Feature", "geometry" : { "type" : "Point", "coordinates" : [ -xx.xxxxxxxxxxxxxxx, xx.xxxxx ...

Enhancing website security using Content Security Policy in conjunction with Google Closure

Implementing CSP for my web application is a top priority. Here's the policy I have in mind: "default-src 'self' gap: cdvfile;" I rely on google closure for my javascript needs. However, it seems that without javascript optimization, my ...

Using AngularJS Scope to Map an Array within a JSON Array

I'm attempting to extract the type and url values from the media2 object within this JSON array and assign them to an AngularJS scope Array. "results":[ { "session2":[ { "__type":"Object", "abou ...

transferring JSON information from the client to the service

In order to incorporate RESTful architecture into an existing SOAP service, I am modifying the service interface by adding WebGet and WebInvoke attributes. These attributes allow for both REST and SOAP compliant services. Following this CodeProject tutoria ...

Unlock the power of json data traversal to derive cumulative outcomes

Our goal is to populate a table by parsing a JSON object with predefined header items. (excerpt from an answer to a previous query) var stories = {}; for (var i=0; i<QueryResults.Results.length; i++) { var result = QueryResults.Results[i], ...

Transforming a form containing recurring elements into JSON

Sorry if this topic has already been discussed, I wasn't able to locate any information I currently have an html form structured like so: <form> <div> First Name <input name="FirstName" type="text"> Age <input name="Age" t ...

In production, make sure to use @JsonIgnore, but remember to include it in your tests as well

In Kotlin, I have a (data) class structured as shown below. When the application is running with the active Spring profile live, my goal is to only show the name. However, when the application is running with the active Spring profile test, I need the ...

The `res.send()` function is showing [object object] and I am unable to access any properties

I've just started learning about REST APIs with express. I am encountering a strange issue where the code successfully console logs { name: 'Test', id: 1 } for the user, but when I send the response, it displays [Object object]. Additionally ...

Converting TCL to JSON: Generating JSON output with huddle in a concise line

Let's take a look at a tcl data in the following format: set arr {a {{c 1} {d {2 2 2} e 3}} b {{f 4 g 5}}} By using the huddle module, we can convert it into Json format: set json_arr [huddle jsondump [huddle compile {dict * {list {dict d list}}} $ ...