How to use Newtonsoft to deserialize a JSON string into a collection of objects in C#

Here is a sample code for a class:

using System;

public class AppEventsClass
{
    public string title { get; set; }
    public string description { get; set; }

}

Imagine retrieving the following JSON string after calling a remote webservice:

{"d":"[{"title": "test", "description": "test desc"}, {"title": "test2", "description": "desc test 2"}]"}

How can you convert this JSON string into a List<> of AppEventsClass using Newtonsoft?

I have attempted various solutions, but none seem to work effectively. For instance, I tried the following:

List<AppEventsClass> result = new List<AppEventsClass>();
result = JsonConvert.DeserializeObject<List<AppEventsClass>>(content).ToList();

Below is an example of the .asmx file that serializes the string:

[ScriptMethod(UseHttpGet = true)]
    public string GetEvents()
    {
        using (mySQLDataContext ctx = new secondosensoSQLDataContext())
        {
            List<eventi> eventiList = ctx.eventi.ToList();
            List<AppEventsClass> eventiClassList = new List<AppEventsClass>();
            for (int i = 0; i < eventiList.Count; i++)
            {
                AppEventsClass a = new AppEventsClass();
                a.title = eventiList[i].titlolo_evento;
                a.description = eventiList[i].descrizione_evento;
                eventiClassList.Add(a);
            }
            var json = JsonConvert.SerializeObject(eventiClassList);
            return json;
        }

    }

Answer №1

It appears that the issue lies in how the response is formatted when retrieved. If we assume the JSON string looks like this:

{"d":[{"title":"test","description":"test desc"},{"title":"test2","description":"desc test 2"}]}

The correct class structure for deserialization should be as follows:

public class Rootobject
{
    public D[] d { get; set; }
}

public class D
{
    public string title { get; set; }
    public string description { get; set; }
}

Thank you.

PS. Here is a working example:

class Program
{
    static void Main(string[] args)
    {
        string json = "{\"d\":[{title:\"test\",description:\"test desc\"},{title:\"test2\",description:\"desc test 2\"}]}";
        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(json);
    }
}

public class Rootobject
{
    public D[] d { get; set; }
}

public class D
{
    public string title { get; set; }
    public string description { 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

Generating JSON output in PHP

I've been struggling to figure out why I can extract some parts of the JSON data but not others... Essentially, I am retrieving JSON from a URL (). In my PHP code (using Laravel5), I have the following: $url = 'https://public-crest.eveonline.co ...

Retrieve JSON data from a web API and transmit it to a partial view using a controller

Currently, my code is set up like this: public ActionResult Search(SearchModel model) { string url = "http://10.0.2.31/testwebapi/api/data"; WebClient wc = new WebClient(); wc.QueryString.Add("forename", model.Forename); ...

Steps for transforming an Array of hierarchical data into the correct JSON format for D3 Tree Region visualization

I am struggling with converting an array of hierarchy data into the correct Object format. Here is what I am trying to convert: [ {"PARENT_ID": 0,"CHILD_ID": 1,"NAME": "Quality","LEVEL_A": 0}, {&qu ...

Encountered a Python interpreter error when attempting to load a JSON file with the json.load() function

In the realm of Python programming, I have crafted this code to delve into a JSON file. import os import argparse import json import datetime ResultsJson = "sample.json" try: with open(ResultsJson, 'r') as j: jsonbuffer = json.loa ...

Implementing jQuery/JavaScript to efficiently iterate through JSON data

I have implemented a form that allows users to select an item from a multi-select dropdown (A). If the desired item is not listed, users can manually add it using another text input box (B). Once added, an AJAX call saves the item to the database. After su ...

Pug: perform a task depending on the presence of an element within a variable

I'm currently working with Express js to create a web application. I make use of an API to fetch some data, which is then sent to a pug file in the following format. res.render('native.pug', {product_name: body.products, cart_items:body.car ...

Using Ruby to filter elements from a complex JSON structure based on specific criteria

Looking to extract all marketID values from markets where the marketName is 'Moneyline'. I've attempted various combinations of .map, .reject, and/or .select methods, but the complex structure is making it challenging to narrow down. The da ...

Creating a dynamic trio of graphs with HTML5, CSS3, and Vanilla JavaScript

I successfully created a tree graph using HTML5 and CSS3, but currently the nodes are static. I am looking to enhance the graph by making it dynamic. By dynamic, I mean that if the number of nodes increases or there are multiple children added, the graph ...

Obtain PHP array after making an AJAX request

I'm using $.post() to send a JavaScript object and I need to receive an array in return. JavaScript Code var ajaxData = {action:"createuser"} $("input[required]").each(function(){ var attr = $(this).attr("name"); ajaxData[attr] = $(this).val ...

The Mongoose query for the id field retrieves both the id and _id values

Within my Mongoose schema, there is a specific field named id which holds a unique identifier for each document. This operates using the same system as the standard _id field as shown below: var JobSchema = new mongoose.Schema({ id: { type:String, requi ...

Utilizing Postgres, explore the effectiveness of substring indexing and matching on JSON string arrays

I am using PostgreSQL and have a table with a jsonb field defined as json JSONB NOT NULL. Within this jsonb field, I have an array of strings, such as: { "values": ["foo", "bar", "foobar"]} To search for rows that c ...

Discovering strings within strings on the Android platform

In my current project, I am dealing with a lengthy JSON text that contains movie titles. I need to extract these titles from the following pattern: ((((((( .","title":" AND ","type":" ))))))) After researching other solutions, I came across one appro ...

Harness the power of Highcharts through an Ajax request to retrieve a JSON file

I am having an issue using Highcharts with a JSON file from an external server. When I try to bind the returning file to the chart in my ASP.NET MVC application, it doesn't work. Here is the code I have attempted: http://jsfiddle.net/Q6ngj/2/ jQuery ...

Creating a personalized serializer using Ember Data for handling JSON data

I am working with a Session object in Ember data that I need to model. The JSON response from the server is fixed and looks like this: { "metadata": { "page": 1, "page_size": 100, "total_num_objects": 7, "total_num_pages": 1 }, " ...

Validating JSON in C# using Regular Expressions

In the scenario that I am presented with a JSON string and need to validate it using C#, it is important to understand the structure of a JSON string. The format typically looks like this: string jsonStr = {"Id":123,"Value":"asdf","Time":"adf","isGood":fa ...

What is the best way to extract the created_time field from this Instagram JSON object?

After receiving this JSON data, I noticed that the created_time value displays the time in integer format instead of a proper time format. How can I convert the created_time into the correct format? "filter"=>"Normal", "created_time"=>"1421677966" ...

What is a way to nest a promise request within another request?

Q: How can I create a new promise within a request, and then return it in a nested request? Here is the code snippet: request({ // --------------request 1------------ url: request_data.url, method: request_data.method, form: request_data.data ...

Implementing Angular *ngFor to Reference an Object Using Its Key

myjson is a collection of various hijabs and headscarves: [ { "support": 2, "items": [ [ { "title": "Segitiga Wolfis", "price": 23000, "descripti ...

The issue persists with json_encode as it fails to display the desired JSON output

<?php include("db_connection.php"); if(isset($_POST['id']) && isset($_POST['id']) != "") { // retrieve User ID $user_id = $_POST['id']; // Retrieve User Details from database $query = "SELECT * FROM prod ...

Laravel integration with JsGrid

I'm relatively new to JsGrid and I'm attempting to implement certain functionalities similar to the one demonstrated at this link in a Laravel project. However, I encountered an error stating "Undefined index: id". I'm trying to retrieve dat ...