Transforming a JSON object into a list in C#

After exploring similar posts without success, I am reaching out here for help.

I have a Json data stored in a hidden field that I am trying to access in the code behind file of my markup page. My goal is to convert this Json into a List and bind it to a grid. However, when I try to deserialize it, I encounter an error stating "Unexpected error encountered while parsing values ''"

Below is the script used to retrieve data from the grid and create a Json object.

function BeforeSorting() {
    var list = UpdateDataSource();
    $("#SortingField").val(list);
}

function UpdateDataSource() {
    var list="";
    var grid = $find("DetailsGrid");
    var rows = grid.get_rows();
    for(var i =0 ; i<rows.get_length();i++){
        var name = rows.get_row(i).get_cellByColumnKey("Name").get_value();
        var country = rows.get_row(i).get_cellByColumnKey("Country").get_value();
        var gender = rows.get_row(i).get_cellByColumnKey("Gender").get_value();
        var age = rows.get_row(i).get_cellByColumnKey("Age").get_value();
        var uniqueKey = rows.get_row(i).get_cellByColumnKey("UniqueKey").get_value();

        list = list + '{"Name":"' + name + '", "Country":"' + country + '", "Gender":"' + gender + '", "Age":' + age + ', "UniqueKey":' + uniqueKey + '},';
    }
    list = "["+list.substr(0, list.length - 1)+"]";
    return JSON.parse(list);
}

The model class definition:

public class Details
{
    public string Name { get; set; }
    public string Gender { get; set; }
    public string Country { get; set; }
    public int UniqueKey { get; set; }
    public int Age { get; set; }
}

The code snippet for deserializing the JSON and retrieving data as a List of the model class.

protected void DetailsGrid_ColumnSorted(object sender, Infragistics.Web.UI.GridControls.SortingEventArgs e)
{
    var dataSource = SortingField.Value;
    List<Details> result = (List<Details>)Newtonsoft.Json.JsonConvert.DeserializeObject(dataSource, typeof(List<Details>));
    DetailsGrid.DataSource = result;
    DetailsGrid.DataBind();
}

The JSON string obtained is shown below:

"[{"Name":"Jerry", "Country":"U.S.A.", "Gender":"Male", "Age":20, "UniqueKey":1},{"Name":"Tom", "Country":"U.K", "Gender":"Male", "Age":10, "UniqueKey":2},{"Name":"George", "Country":"Gremany", "Gender":"Male", "Age":38, "UniqueKey":3},{"Name":"Kate", "Country":"France", "Gender":"Female", "Age":40, "UniqueKey":4},{"Name":"Jenny", "Country":"Poland", "Gender":"Female", "Age":25, "UniqueKey":5}]"

Answer №1

initialize a list as an array and populate it with JavaScript objects, then use JSON.stringify to convert it to JSON format

function UpdateDataSource() {        
    var grid = $find("DetailsGrid");
    var rows = grid.get_rows();
    var list = [];
    for(var i =0 ; i < rows.get_length(); i++){
        var item = {
            Name : rows.get_row(i).get_cellByColumnKey("Name").get_value(),
            Country : rows.get_row(i).get_cellByColumnKey("Country").get_value(),
            Gender : rows.get_row(i).get_cellByColumnKey("Gender").get_value(),
            Age : rows.get_row(i).get_cellByColumnKey("Age").get_value(),
            UniqueKey : rows.get_row(i).get_cellByColumnKey("UniqueKey").get_value()
        };

        list.push(item);
    }
    return JSON.stringify(list);
}

A more concise way to deserialize the JSON and retrieve data in a list of the model class is shown below

protected void DetailsGrid_ColumnSorted(object sender, Infragistics.Web.UI.GridControls.SortingEventArgs e) {
    var dataSource = SortingField.Value;
    var result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Details>>(dataSource);
    DetailsGrid.DataSource = result;
    DetailsGrid.DataBind();
}

Following @Andreas' suggestion, the UPDATE function should yield the same output.

function UpdateDataSource() {        
    var grid = $find("DetailsGrid");
    var rows = grid.get_rows();
    var list = rows.map(function(row) {
        return {
            Name: row.get_cellByColumnKey("Name").get_value(),
            Country: row.get_cellByColumnKey("Country").get_value(),
            Gender: row.get_cellByColumnKey("Gender").get_value(),
            Age: row.get_cellByColumnKey("Age").get_value(),
            UniqueKey: row.get_cellByColumnKey("UniqueKey").get_value()
        };
    });
    return JSON.stringify(list);
}

Answer №2

This solution looks like it should work

private void SortDetailsGrid(object sender, Infragistics.Web.UI.GridControls.SortingEventArgs e)
{
    var dataSource = SortingField.Value;
    List<Details> result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Details>>(dataSource);
    DetailsGrid.DataSource = result;
    DetailsGrid.DataBind();
}

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

Creating a personalized context menu in Javascript: The ultimate guide to incorporating copy and paste features

We are developing a unique context menu for our online text editor, complete with copy/paste options. However, we encountered difficulties accessing the system clipboard from within the browser. It once seemed impossible to achieve this, as discussed in th ...

Encountering a Blank Area at the Top of a Printed AngularJS Screen

Currently, I am tackling an issue in AngularJS while working on the Print Invoice Page. The problem I am encountering is a blank space at the top of the printed screen. Check out the image here Below is my code: HTML <div id="invoice" class="compact ...

How can I loop through this MongoDB JSON data in a Pug template?

I am trying to display the data from my MongoDB JSON in a specific format shown below: index date 1 1/18/2019, 11:10:05 PM 2 1/18/2019, 11:10:19 PM 3 1/18/2019, 11:13:29 PM This is the MongoDB code snippet: { "_id" ...

"Trouble arises with the match() function in relation to email regex validation

After retrieving the HTML content from a website with my function, I am using String.prototype.match along with a regex rule to extract email addresses from that page. However, the issue is that I am receiving a line that matches the regex but does not con ...

Utilize JSON data to dynamically populate TextFields or Select menus depending on a specific key in the JSON object

As I retrieve multiple JSON groups from an API, each group contains one or more questions objects. The task at hand is to attach each question along with its corresponding response to a textField. Based on the value of QuestionType, it will be decided whet ...

Utilize Bootstrap4 to position content above the navigation icon

I need assistance to modify my code so that it will have the following appearance: I successfully created a navigation bar icon and inserted the logo, but I am struggling to position the data above the navigation icon: My current code: <nav class="n ...

Discovering the power of ng-change in an Angular typeahead search functionality

I am facing an issue with displaying the result list when searching for users on key press using customTemplate.js. The list is not showing up after the first key press. Below is the code I am using: <input type="text" placeholder="Search people here ...

difficulty receiving the information promptly via an AJAX request (utilizing AJAX and the 'for' loop)

Currently, I am successfully retrieving data from an ajax call for individuals. However, my next task is to retrieve multiple sets of data simultaneously. Here is the code snippet: for(var i = 1; i <= 2; i++){ console.log(i); $.ajax({ url: cal ...

Is AngularJS not able to effectively manage the button type "reset"?

I currently have the following code snippet: <form name="editor"> <h2>Create/Update</h2> {{ editor.title.$error.required }} <div ng-class="{ 'has-error': editor.title.$invalid && editor.title.$dirty, &apo ...

Eliminate the need for background video buffering

I have a piece of code that I'm using to remove all the created players for my video elements. The code works fine, but I'm facing an issue where the video keeps buffering in the background after it's changed via an ajax call success. Can yo ...

What methods can be used to secure Next.js API routes and prevent them from being directly accessed through the URL

I am seeking a solution for concealing the response data of next.js API routes when accessed through URL. I need to protect certain sensitive information from direct access by users. ...

Identifying whether a Alphabet or a Digit has been Pressed - JavaScript

I understand that it is possible to detect if a key has been pressed and identify which key was pressed using JavaScript. In order to check if a key is down or pressed, jQuery can be utilized with ease: $( "#some id" ).keydown(function() or $( "#m" ). ...

Retrieving blog posts formatted in markdown from a centralized JSON file

My current setup involves using react-markdown to load markdown content from a JSON file. I have opted for a static site hosted on CloudFront to save money and eliminate server operation costs. All posts are compiled into a posts.json file which is then ...

The JavaScript function I created to remove the last item in an array is not functioning correctly when it encounters an "else

My button has been designed to delete the last index from this.fullformula, which is a string. However, I've encountered an issue with deleting characters from this.result, which is an integer. Instead of looping over the function, it only deletes one ...

What is the best way to display a JSON array in Angular 4?

Check out this JSON structure: -------------------------------------------------- "id": 2, "user": { "id": 1, "name": "User", "surname": "User", "email": "<a href="/cdn-cgi/l/email-protection" ...

Is there a way to load all movies in advance when none of the tags are selected?

In my current project, I am working on a feature that involves an array of movie objects. Each movie has a name and tags assigned to it. I want to be able to display movies based on the tags selected by the user. For example, if the user selects the tag "c ...

Update or overwhelm a node_module file reference

Let's say I have an installed node_module called magicalModule, which was installed using the command npm i magicalModule. To use it in my code, I import it like this: const magic = require('magicalModule'). Now, is there a way for me to o ...

Encountering an 'undefined' property error when clicking a button in Angular 1.x

Hey there, I have a question that might seem simple to some of you. I'm struggling with fixing an error and I don't quite understand why it's happening :( This error popped up while using Angular 1.x. What I need help with is creating an al ...

What is the best method for constructing an array of sets using Raphael?

This code snippet creates a total of 48 squares, each labeled with a number from 0 to 47 within them. Utilizing sets is the recommended method for achieving this on stackoverflow. By grouping the rectangle shape along with its corresponding number, it allo ...

Error: Unable to access the 'rotation' property of an undefined object in the animate function on line 266 of index.html, at line 287 of index.html

I am facing an error when trying to animate a model with rotation or position in my code. I attempted to create an init function to run everything, but it did not resolve the issue. The error only appears during animation; once the animation stops, the e ...