Looping through a JSON object within the server environment

If I have a basic model set up like this:

public class User
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string Age { get; set; }
}

and let's say I receive a JSON object structured as follows:

var users = {
    items: [
        { id: "1", name: "John", age: "25"}
    ]
};

and when passing it to a WebMethod like this:

Project.Web.Services.AJAXService.Save(JSON.stringify(users), function (result) {
    //
});

How can I properly parse it on the server side so that I can iterate through it using a foreach loop?

I attempted the following:

[WebMethod(true)]
public void Save(string usersJson)
{
    List<User> users = JsonConvert.DeserializeObject<List<User>>(usersJson);

    foreach (var user in users)
    {
        string info = user.Name;
    }
}

However, an Exception is thrown with the message:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Project.Data.Models.User]' because the type requires a JSON array (e.g. [1,2,3]) to be properly deserialized.

edit: After learning more from this post, I realized that it is actually not pure JSON but rather JavaScript object literal notation. Although, my goal remains to accurately interpret the existing data structure.

edit2: Here is the content of the usersJson:

"{\"items\":[{\"id\":\"1\",\"name\":\"John\",\"age\":\"25\"}]}"

Answer №1

Utilize the following code snippet for deserialization

JsonConvert.DeserializeObject<Root>(peopleJson);

public class Root
{
    public List<Person> items { get; set; }
}

Answer №2

The issue lies within the items wrapper. It needs to be updated to:

JsonConvert.DeserializeObject<ListOfPersons>(peopleJson)

with the following structure:

public class ListOfPersons
{
  public Person[] Items {get; set;}
}

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

Deprecated: Asynchronous XMLHttpRequest on the primary thread is no longer supported

Currently, I am working on the extjs framework. I have developed an application using extjs. However, whenever I launch the application in the browser, I encounter some warnings in the console. The warning message states that Synchronous XMLHttpRequest o ...

"Alert: Jest has detected that an update to MyComponent in a test was not properly enclosed in an act() function, even though there was no actual update being made. Please

Here's a super straightforward test I've put together: it('renders', () => { const { toJSON } = render( <MockedProvider> <MyComponent /> </MockedProvider> ) expect(toJSON()).toMatc ...

Ignoring Json in ASP .NET doesnt appear to be functional

Issue Encountering difficulties with serializing an object in MVC .Net when returning a json result due to loop references. Error message: Self referencing loop detected for type ... Defining my entity class: public class Subscriber { [JsonIgnore] ...

Creating a custom directive to mimic the behavior of ng-if

Hey there! I've got this cool directive that lets you conveniently hide or show elements: <div cdt-visible-to="Admin,Moderator">...</div> By using this directive, our HTML code becomes more declarative. Here's a snippet of what the ...

Show or hide a div through two variables that toggle between different states

It's possible that I'm not fully awake, so missing the obvious is a possibility. However, I have 2 variables that determine whether a div has a specific class or not. The class functions more like a toggle; so the following conditions should tri ...

Is there internal access to the "access property" within the "data property" in JavaScript?

I have come to understand that there are two types of properties in objects: data properties and accessor properties. It is possible to access the "data property" without using an "accessor property," as shown below: const person = { name: 'Pecan&a ...

Dealing with a NullPointerException problem in Java

Having trouble with a pesky NullPointerException. During my debugging process, I discovered that the element is not null, but I seem to be encountering an issue in the first IF statement and I can't quite pinpoint the problem. Initially, I suspected ...

What could be the reason for encountering TypeScript within the Vue.js source code?

While exploring the vue.js source code, I stumbled upon some unfamiliar syntax that turned out to be TypeScript after further investigation. What baffled me was finding this TypeScript syntax within a ".js" file, when my understanding is that TypeScript ...

Choose HTML elements

Can anyone help me find an element and extract a complete block of HTML? I attempted the following: $(this).find('h1').html(); However, I only managed to retrieve the text within the h1 tag... What could I be overlooking? ...

What is the best way to add two strings with indexes and points to a Three.js BufferGeometry?

I have a massive database containing tens of thousands of objects with various types of information, including their 3D meshes. Currently, I am attempting to display these objects in web browsers using Three.js. The object information is provided by anoth ...

AngularJS allows you to dynamically update a list by adding elements to the end as

I have a specific requirement to showcase a lineup of elements in a single row, granting users the ability to scroll through them. Upon reaching the end of the scroll, a function should be triggered to add more elements to this lineup. I've successfu ...

Guide for displaying an image exclusively on the front side of a JSON model object using Three Js

Hey there, I've been working on rendering an image onto a model object using a JSON file. While I've successfully rendered the model itself, I'm facing an issue with getting the image to render from the JSON file. var loader1 = new THREE.As ...

A guide on leveraging React TypeScript to pass components as props

Currently, I am in the process of learning React combined with TypeScript. However, I have encountered a challenge that I need assistance with. The issue stems from a parent component: import React from 'react'; import TestPropsComponent from & ...

How can I remove just one specific card from an array when transferring it onto another card, without deleting all of them?

I'm currently working on a project where I am mapping out an array to create cards with object properties. However, I am facing a problem where clicking on the "Not Interested" button (which acts as a delete post button) is causing all the posts to be ...

Elements are unresponsive to scrolling inputs

My Ionic 2 input elements are not scrolling to the top when the keyboard is shown. I've tried everything I could find on Google, making sure the keyboard disable scroll is set to false. However, I still can't figure out what's causing the sc ...

Selecting the appropriate fields based on the value of another field

Is there a way to use Jolt to select only fields that contain the value of another field? Below is my input: { "type": "A", "field1": "value1", "field2": "value2", "example1-A1[zone= ...

Manually detecting changes in the query string using AngularJS

My AngularJS application includes an edit form with a routing URL like app/edit/:id. When I navigate to app/edit/5, I am able to edit the object with ID 5. However, if I manually change the URL to app/edit/6, the application loads the object with ID 6 in ...

What is the best way to transition a connected component from a class-based to a functional component in TypeScript?

I'm in the process of switching from a class-based component to a functional component. This is a connected component that uses mapState. Here is my initial setup: import { connect } from 'react-redux' import { fetchArticles } from '. ...

What is the process for retrieving information from a particular section of a Wikipedia page with the help of the Wikipedia API?

I am currently working on creating an android app and I am in need of extracting the Nutrients section of a specific vegetable or fruit from Wikipedia to display in my app. https://i.sstatic.net/avaGA.png This is my progress so far... I am attempting to ...

Unexpected anomaly with Jquery's after() method

Currently, I am working on the following task: I want to dynamically add a new student to a table of existing students using AJAX when a student is added through my user interface. The process involves sending the UI input fields to the controller, which ...