Guide to properly deserializing a JSON string into a class with a nested List of different class members

I have a scenario where I am sending a JSON stringified "View" object from the browser to an ASP.Net Page Method using Jquery's $.Ajax(). The issue I am facing is that while the Javascript deserialization is successful for all the strings and integers in the View class, the List<DataItem> remains empty.

To troubleshoot, I used the stringified JSON in the Chrome dev tools to create a unit test. I tried deserializing it using both the DataContractJsonSerializer and the JavaScriptSerializer. Surprisingly, the DataContractJsonSerializer correctly deserialized my object graph while the JavaScriptSerializer did not fetch the List data. How can I ensure the correct deserialization on my page method?

public class View
{
    public string Text { get; set; }
    public string AnotherText { get; set; }
    public Int SomeInt { get; set; }
    public List<DataItem> { get; set; }
}

public class DataItem
{
    public Person person {get;set}
}

public class Person
{
    public int Age {get;set}
}

   var dataa = {mqvm: mqvmJSON };
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify( dataa ),
        url: "GoHere.aspx/WebMethodName",
        success: function(data) {
            alert(data.d);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText + ' ' + errorThrown);
        }
    });

If I want to receive the data as a string parameter instead of the view object:

    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    [WebMethod]
    public static string CreateResponseReview(string mqvm)
    { 
        //do manual JSON deserialization here.

        return "Success";
    }

Here is an example of how my JSON object looks:

    {
    "Text": "6",
    "AnotherText":"wow"
    "SomeInt": 5,
    "DataItem":[
        {
            "person":{
                "Age":23
            }
        },
        {
            "person":{
                "Age":42
            }
        }
    ]
}

Answer №1

After much trial and error, I finally cracked the code.

Avoiding the JavascriptSerializer class proved to be a wise decision as it mishandled my nested list. Instead, I opted to receive the object as a string and manually deserialize it. The hurdle I faced was the infamous "no parameterless constructor defined for type of u0027system.string u0027" error.

It dawned on me that the apostrophe in U0027 might be causing confusion for the runtime, mistaking it for a type called "System.string" instead of System.string. The root of my issue lay in the mishandling of parameters in the data2 item below. To rectify this, I had to encompass both the key and the value in single quotes.

function requestHtmlFromServer(mqvmJSON) {
    var mqvmstring = JSON.stringify(mqvmJSON);
    var data2 = "{\'mqvm\':\'" + mqvmstring + "\' }"; \\<--the problem
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: data2,
        url: "MedicalInformation.aspx/CreateResponseReview",
        success: function(data) {
            alert(data.d);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText + ' ' + errorThrown);
        }
    });
}


    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    [WebMethod]
    public static string CreateResponseReview(string mqvm)
    {
        string noNewLines = mqvm.Replace("\n", "");
        View viewModel = ToObjectFromJSON<View>(noNewLines);
        //do my other stuff here

        return "Success";
    }
    public static T ToObjectFromJSON<T>(string jsonString)
    {
        var serializer = new DataContractJsonSerializer(typeof(T));
        var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
        var newObject = (T)serializer.ReadObject(memoryStream);
        memoryStream.Close();
        return newObject;
    }

Answer №2

Consider the following approach:

Deserialization Example

string jsonData = "{\"text\":\"some content\",\"additionalText\":\"more content\", \"numberValue\":1, \"itemList\":[{\"individual\":{years:25}},{\"individual\":{years:20}}]}";

JavaScriptSerializer deserializer = new JavaScriptSerializer();
View viewer = deserializer.Deserialize<View>(jsonData);

Object Classes

public class View
{
    public string TextData { get; set; }
    public string AdditionalText { get; set; }
    public int NumberValue { get; set; }
    public List<DataItem> ItemsList { get; set; }
}

public class DataItem
{
    public Person Individual { get; set; }
}

public class Person
{
    public int Years {get;set;}
}

JSON Structure

{
    "text":"some content",
    "additionalText":"more content", 
    "numberValue":1, 
    "itemList":
        [
            {"individual":{years:25}},
            {"individual":{years:20}}
        ]
}

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

Is it possible to use uglifyjs to merge multiple files into a single minified file?

I attempted to compress multiple javascript files into one using the uglifyjs tool, but encountered an issue. I ran $node uglifyjs.js to execute the file. Below is the content of the uglify.js file: var fs = require('fs'); var uglifyjs = re ...

Creating an app for sending text messages and making video calls with Spring Boot technology

I am interested in developing an application with Spring Boot that allows users to make video calls and share text messages. I also want the ability to save these videos for future viewing by registered users of the app. Although I am familiar with node.j ...

Difficulty retrieving information using AngularJS service post selection of item

Currently, I am working on a project involving an AngularJS application. While using the service testPanelService, I encountered a problem where selecting an item from a list correctly logs the details of the selected item. However, when attempting to fetc ...

Why won't both routes for Sequelize model querying work simultaneously?

Currently, I am experimenting with different routes in Express while utilizing Sequelize to create my models. I have established two models that function independently of one another. However, I am aiming to have them both operational simultaneously. A sea ...

Detecting when the Ctrl key is pressed while the mouse is hovering over an element in React

In my project, I have implemented a simple Grid that allows users to drag and drop items. The functionality I am trying to achieve is detecting when the mouse is positioned on the draggable icon and the user presses the Ctrl key. When this happens, I want ...

Issues with React Router functionality on a live production site are causing complications

I recently created an Amazon-clone UI using create-react-app, but it only displays dummy data. The issue arises after deploying it to Vercel - the routing does not function as expected. When clicking on links, a blank page appears with correct URL paramete ...

Ways to retrieve and contrast the border style of an image utilizing javascript

I'm currently attempting to identify images on my webpage that have the style border: 1px #c6c6c6 solid; let images = document.getElementsByTagName('img'); for (let i = 0; i < images.length; i++) { if (images[i].style.border === "1px ...

javascript problem with class method for loading json file

I've encountered an issue with my class setup below. Despite most things working, the console keeps throwing an error when json.onload is triggered. The error message reads "Uncaught TypeError: Cannot read property of 'push' of undefined". ...

Encounter the following issue: Unable to access property '0' due to being undefined

After restructuring my entire Javascript code, I managed to solve the problem with asynchronous calls. However, an error occurs when editing a repair and the server prompts the client for repair information again. The error message displayed is "Uncaught ...

Facing issue with local redis session not functioning as intended

I'm encountering an issue with my redis session not functioning properly when testing locally. EDIT: Additionally, I realized that it's failing to save a cookie when trying to set req.session[somekey] as undefined like so: req.session.user = u ...

Is there a way for me to receive user inputs, perform mathematical operations on them, and then display the result of the calculation? Additionally, is there a way to ensure that the output value automatically updates

As a newcomer to HTML and JavaScript, I'm unsure how to approach this task. Here is what I have so far: <div class="inputs"> <label for="#arena2v2">2v2 Arena Rating:&#9;</label><input class="pvp" type="number" step="1" m ...

employ varying XSL stylesheets to display an XML document in a separate window

My issue involves an XML file being transformed by a specific XSL file (XSLT 1.0), which in turn includes multiple other XSL files with various templates. The challenge is to add a button to the rendered XML that, when clicked, opens the same XML in a ...

Exploring the Variances Between ChromeDriver and RemoteWebDriver

Currently, my .Net/C#/Selenium project is divided into two branches for mobile and web versions. I am facing errors while trying to consolidate them into one branch due to issues with setting up the web driver. The mobile version, which connects to a physi ...

What are the steps for implementing secure login and authorization process in Oracle's RESTful web services?

Currently, I am utilizing Oracle RESTful Web Services within Oracle APEX to retrieve data from the Oracle database. While I am familiar with fetching data using Oracle web services, I am struggling to determine how to properly send a username and password ...

Unable to access API endpoint for retrieving items as described in the Express/React tutorial on Pluralsight

Currently, I am going through a tutorial on React, Express, and FLUX. Unfortunately, I have encountered a roadblock in the form of a CANNOT GET error when trying to access my API data. https://i.stack.imgur.com/RbUzf.png In the server file under Routes & ...

Encountering an error while transmitting variables through ajax

Encountering an issue when attempting to remove a user from the database. Below is the code I have written: On the server side: @RestController public class EmployeeRestController { @DeleteMapping( value = "/delete_user") public List<Em ...

The condition is not established by the Firestore where clause

I'm working on a function that includes two where clauses. My objective is to verify the existence of a document based on the presence of two specific IDs. However, when I execute the function, it retrieves all the records in the collection instead. C ...

Tips for efficiently updating a nested object in MongoDB without overwriting any existing fields that are not referenced

Currently, I am utilizing C# within the dot net framework to manage simple collections in MongoDB. Although I am new to NoSQL and have mainly worked with MySQL before, I can handle creating and updating collections without much difficulty. However, a chall ...

Can you tell me the title of this pointer?

When utilizing the drag function in the RC-tree, a specific cursor is displayed. I am interested in using this cursor in another dragzone on my website, but I am uncertain of its name. This same cursor also appears when dragging highlighted text into the b ...

What are the steps to connect to multiple databases with ExpressJS?

I have a server with 3 databases containing identical tables. The databases are named DB1, DB2, and DB3. When working with a specific database, I utilize the following code in app.js: var cnxDB = require('./routes/cnxDB'); app.post('/user ...