Converting a Jsonstring to a listObject in C# - A step-by-step

I am attempting to convert a Jsonstring into a c# listObject. The data is being sent from JavaScript using the following code:

params = "data=" + JSON.stringify(queryResult.$$rows);      
XHR.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  
XHR.setRequestHeader("Content-length", params.length);      
XHR.setRequestHeader("Connection", "close");
XHR.send(params);

Then in ASP.NET, I am trying to deserialize the Jsonstring with:

public class HomeController : Controller
{
    [HttpPost]
    public ActionResult doWork(string data) 
    {
        var dump = JsonConvert.DeserializeObject<List<RootObject>>(data);
        return new EmptyResult();
    }   
}



public class RootObject
{
    public string data { get; set; }
    public string text { get; set; }
}

Upon inspecting the local variable data, I can see a valid json string:

[  
   [  
      {  
         "data":"Australia",
         "text":"Australia"
      }
   ],
   [  
      {  
         "data":"China",
         "text":"China"
      }
   ],
   [  
      {  
         "data":"Hong Kong",
         "text":"Hong Kong"
      }
   ],
   [  
      {  
         "data":"Indonesia",
         "text":"Indonesia"
      }
   ],
   [  
      {  
         "data":"Netherlands",
         "text":"Netherlands"
      }
   ]
]

However, when ASP.NET attempts to execute JsonConvert.DeserializeObject>(data); it results in an error message:

JsonSerializationException was unhandled by user code an exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in newtonsoft.Json.dll but was not handled in user code

Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'maps.Controllers.RootObject' because the type requires a JSON object (e.g. {"name" : "value"}) to deserialize correctly.

How can I resolve this issue? And is this the correct approach in JavaScript?

Answer №1

string jsonData = @"[  
[  
    {  
        ""data"":""Brazil"",
        ""text"":""Brazil""
    }
],
[  
    {  
        ""data"":""India"",
        ""text"":""India""
    }
],
[  
    {  
        ""data"":""Japan"",
        ""text"":""Japan""
    }
],
[  
    {  
        ""data"":""Mexico"",
        ""text"":""Mexico""
    }
],
[  
    {  
        ""data"":""Spain"",
        ""text"":""Spain""
    }
]
]";
var parsedResult = JsonConvert.DeserializeObject<List<RootObject>[]>(jsonData);

Your desired outcome has been achieved

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

Can MVC2 JSON output contain cookies?

Is it possible to retrieve cookies when returning a Json result in MVC2? ...

Issue: AngularJS not refreshing view after receiving server response

Currently, as I work on developing a mobile application, I've come across an issue related to relaying messages in the view after executing an ajax call and receiving data from the server. My goal is to display these messages to users only after they ...

The process of creating a React build varies greatly from the initial development phase

Thank you for offering to help me! After building my React web app, it looks very different from development mode. I use serve -s build to monitor the app build. However, even on my online DigitalOcean server, it doesn't appear the same as in develop ...

From PHP to JavaScript, the looping journey begins

Question I am attempting to display markers on a map using PHP to fetch the data, then converting it into JavaScript arrays for marker addition. Below is an example of my code: Database query require_once("func/connect.php"); $query = "SELECT * FROM sit ...

What is the process for creating a dynamic URL, such as example.com/profile/CroatiaGM?

I am in the process of developing a user control panel, and I have encountered some difficulties with creating a dynamic profile link. For instance, how can I achieve something like example.com/profile/CroatiaGM? Given that my website is primarily coded ...

Enclose the text entered by the user within a newly created element inside a contentEditable division

My current setup includes a contentEditable div like this: <div id="content" contentEditable="true"></div> What I want to achieve is for any text typed by the user to be automatically wrapped within div or p tags. While I can add HTML code to ...

The Android app is experiencing issues with sending the JSONArray post

My experience with using Postman has been smooth and successful. https://i.sstatic.net/SvkK4.jpg However, when attempting to post from the app, only the table and cost object are being posted. This is the Android code snippet I am using: JSONObject sen ...

Using Entity Framework Core to run raw SQL queries ensures that the same code can be used for both SQL Server

Currently, I am utilizing two distinct types of connections: SQLConnection for regular operations and SqliteConnection for integration testing when inserting new exceptions into my LogService. Due to the lack of access to the database context class, I am ...

Is there a way to preserve line breaks when programmatically copying text to the clipboard with JavaScript?

Utilizing Javascript alongside a duo of devexpress asp.net controls to dynamically duplicate the contents of an ASPxMemo (multiline textfield) and assign those contents as the body of an email. The copying and pasting is functioning correctly for the most ...

The jQuery scrollTop function does not account for the height of a slideUp div

My website features a collection of news items, such as alerts and announcements, each wrapped within their own <div> tags. Initially, only the headline of each item is visible on page load. When a user clicks on a headline (h2), the details for that ...

I am interested in developing a program using Javascript or JQuery that can effectively capture the anchor text within <a></a> link tags

I want to automatically capture the link on my website and create a system where, when users click on a specific link, it opens the captured link in a new tab without requiring browser permission and replaces the current tab with a different link. For exa ...

Viewing HTML files remotely using Kendo UI Mobile

I developed a sample hybrid app using the Telerik App Builder CLI. The project features an initial home screen loaded from a COMPONENTS folder within the project. Within the Components folder, there is a Home folder containing an index.js and view.html fil ...

Tips on using the ref attribute in Vue.js to focus on an input element

In my Vue.js component for 2FA, I have implemented the following structure: <template> <div :class="onwhite ? 'on-white' : ''"> <input :id="`n1`" ref="n1" v-model=&quo ...

Unable to configure C# Selenium ChromeOptions to modify the default download directory

How can I ensure that a file is downloaded to a specific location each time, instead of the default downloads folder? Is there another Chrome option that could resolve this issue? ChromeOptions chromeOptions = new ChromeOptions(); chromeOptions.AddUserP ...

Issue with local image on Vue.js slider causing malfunction

Hey, I came across this awesome Vue.js image slider on "digitalocean.com" but it seems to only work with images uploaded on platforms like imgbb, pixabay, etc. I tried to use a local image from my assets folder, but it's not working. Can anyone help m ...

A guide on dynamically checking the checkbox values in each row of a table using JavaScript or jQuery

My table is dynamically populated with values from a database using the following code: var row = table.insertRow(i); i = i+1; // Insert new cells (<td> elements) at the 1st and 2nd position of the new <tr> element: var cell1 = row.insertCell ...

guaranteed function to retrieve React elements

Is there a solution for the issue where if-else doesn't work in run build but works in run dev? The only way I've found to make it work is by using a react hook, but I'm unsure which one to use and where to implement it. import { useAdd ...

When the size is adjusted, seamlessly swap out the current image for a new one without the need to refresh the page

I am currently in the process of developing a website. As part of this project, I am utilizing a bootstrap carousel to display images dynamically based on the screen orientation. Using JavaScript, I am capturing the width and height of the screen and sen ...

Property is not accessible in the componentDidMount lifecycle method

I am having trouble using redux to fire an actionCreator and get my initial data when the app loads. The actionNoteGetLatest function is not recognized as a prop. Can someone assist me with this? In the code snippet provided below, I attempted to call act ...

The Notebook Unreadability Issue arises with an error message indicating that the notebook does not seem to be in JSON format: u'{ "cells": [ { "cell_type": "...',

Encountering a peculiar error while trying to load my ipython notebook. This error is new to me, and I cannot recall doing anything out of the ordinary with ipython: Unreadable Notebook: /path/to/notebooks/results.ipynb NotJSONError('Notebook does no ...