How to Deserialize JSON with numerical keys using Json.NET

Is there a way to convert the provided JSON data into an object using Json.NET? The issue I am facing is that the class name must start with a number.

One example of such a scenario is when using the Wikipedia article API. By making a request through the API endpoint, you receive a JSON response similar to the one below. Take note of the value "16689396" within the "pages" section.


{
   "batchcomplete":"",
   "continue":{
      "grncontinue":"0.893378504602|0.893378998188|35714269|0",
      "continue":"grncontinue||"
   },
   "query":{
      "pages":{
         "16689396":{
            "pageid":16689396,
            "ns":0,
            "title":"Jalan Juru",
            "extract":"<p><b>Jalan Juru</b> (Penang state road <i>P176</i>) is a major road in Penang, Malaysia.</p>\n\n<h2><span id=\"List_of_junctions\">List of junctions</span></h2>\n<p></p>\n<p><br></p>"
         }
      }
   }
}

What is the solution for deserializing this JSON data which includes a dynamic number linked to the article?

Answer №1

If you need to update the Pages property in your Query class, consider using either a Dictionary<int, Page> or Dictionary<string, Page>.

Below is an example implementation based on the provided JSON data - certain names have been assumed for clarity:

// Imports
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

// Classes
public class Root
{
    [JsonProperty("batchcomplete")]
    public string BatchComplete { get; set; }
    [JsonProperty("continue")]
    public Continuation Continuation { get; set; }
    [JsonProperty("query")]
    public Query Query { get; set; }
}

public class Continuation
{
    [JsonProperty("grncontinue")]
    public string GrnContinue { get; set; }
    [JsonProperty("continue")]
    public string Continue { get; set; }
}

public class Query
{
    [JsonProperty("pages")]
    public Dictionary<int, Page> Pages { get; set; }
}

public class Page
{
    [JsonProperty("pageid")]
    public int Id { get; set; }
    [JsonProperty("ns")]
    public int Ns { get; set; }
    [JsonProperty("title")]
    public string Title { get; set; }
    [JsonProperty("extract")]
    public string Extract { get; set; }
}

// Main Test Class
class Test
{
    static void Main()
    {
        // Read JSON file
        string text = File.ReadAllText("test.json");

        // Deserialize JSON to object
        var root = JsonConvert.DeserializeObject<Root>(text);

        // Output specific page title 
        Console.WriteLine(root.Query.Pages[16689396].Title);
    }    
}

Answer №2

Check out this related question about deserializing JSON from wikipedia API using C#

To make the necessary changes, you'll want to switch from using a class for the pages to a dictionary. This allows for a more dynamic approach to handling naming conventions.

Here are the class definitions:

public class PageValue
{
    public int PageId { get; set; }
    public int Namespace { get; set; }
    public string Title { get; set; }
    public string Extract { get; set; }
}

public class Query
{
    public Dictionary<string, PageValue> Pages { get; set; }
}

public class Limits
{
    public int Extracts { get; set; }
}

public class RootObject
{
    public string BatchComplete { get; set; }
    public Query Query { get; set; }
    public Limits Limits { get; set; }
}

For deserialization, use the following code snippet:

var root = JsonConvert.DeserializeObject<RootObject>(__YOUR_JSON_HERE__);
var page = responseJson.Query.Pages["16689396"];

Answer №3

If you want to customize the way JSON is deserialized, you have the option of creating your own Deserializer or modifying the JSON data prior to deserialization.

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

Ways to emphasize a particular <li> element?

Currently, I am delving into the world of React and facing a challenge. I have been trying to solve the issue below: When fetching some JSON data, it appears in this format: [ { "answerOptions": [ "Answer A", "Answer B", ...

Fetching weather data from the Darksky.com API in JSON format

My goal is to retrieve weather data in JSON format from the Darksky.com API. To do this, I first successfully obtained my latitude and longitude using the freegoip.com API. However, the Darksky API requires both longitude and latitude before it can provid ...

Steps for converting an HTML form into a sophisticated JavaScript object

Is it possible to transform a form into a complex JavaScript object based on a structured form layout? I am not sure if there is a better way to accomplish this, but essentially what I am looking for is the following scenario: <form> <input n ...

Manipulating web elements by traversing through selected identifiers in LocalStorage and eliminating them from the document layout

I have a multitude of localStorage keys, including ones labeled Cart, Viewed, and Trash. There are two aspects to my query: 1) What is the most efficient way to loop through the item IDs in localStorage and add a class or data attribute to the correspond ...

Swift - Transforming an NSMutableArray into an array of MKAnotationViews

Currently, I have an array of BarAnnotation objects like this: var bars = [BarAnnotation(latitude: 42.022352, longitude: -93.650413, name: "Micky's Irish Pub", deal: "$2 Drinks 9PM-1AM"), BarAnnotation(latitude: 42.021948, longitude: -93.650348, ...

Passing a JavaScript variable to PHP resulted in the output being displayed as "Array"

After sending a JavaScript variable with the innerHTML "Basic" to PHP via Ajax and then sending an email with that variable, I received "Array" instead of "Basic". This situation has left me puzzled. HTML: <label class="plan-name">Plan name: <b ...

What is the method for retrieving a PHP JSON variable value and displaying it in HTML?

Using the graph API, I managed to retrieve my Facebook friend list and received a JSON array as a response. The value of that array is stored in a variable like this: $json_output=($result['summary']['total_count']); echo "$json ...

Information released by JavaScript through AJAX and JSON

Hello everyone, I've been trying to merge two different Ajax codes together and it's been quite a challenge. As a novice, I know I may sound ridiculous but I really need some help... My goal is to convert an array into JSON and display the data ...

Steps to prevent inputting an entire JSON object into a sole field in AWS Athena

Currently, I am trying to import JSON data from S3 into an Athena table. The structure of my JSON data is as follows; [{"a":"a_value", "b":"b_value", "my_data":{"c":"c_value", "d&q ...

Exploring the extraction of dual values from a deeply nested JSON string using Jackson

I'm currently using the Jackson library for deserializing JSON data. Specifically, I am trying to extract only two values from this JSON - c1 and d1. Here is a snippet of the code I have used so far... How can I retrieve the correct approach to access ...

Azure Function: Eliminate duplicate data in JSON from two many-to-many relationships into a single table

I am facing an issue where I have multiple many-to-many tables mapping to a single table, resulting in duplicate data that needs to be removed from the JSON output. Additionally, the Ingredients and Conditions are displayed as lists, causing duplication of ...

I incorporated JSON into my codeigniter project as follows

Here is the code snippet $.post("color/color1", {color : e}, function(data) { var out=data + "<a class='one'>total</a>"; console.log(out); output.html(out); } This is the resulting content as displayed by the browser ...

How to effectively utilize the Twitter API with C# - a comprehensive guide

Seeking guidance on utilizing the Twitter API with C#. Currently struggling to find relevant information. ...

Receiving NullReferenceException when attempting to access Firefox logs with Selenium in c#

I am currently working on a project that involves recording log files in Firefox using Selenium with c#. To test this functionality, I have created a basic example to open a browser and retrieve the logs. However, I encountered an issue with a 'Obje ...

Using JSON data in a Flask template

Looking to work with JSON data: { "name": "Jo", "surname": "Sin", "market": "US", "date": "2020-07-07T00:00:00", "contactPerson": { "name": "Ja ...

What is the best way to handle parsing a JSON object in a single response?

My challenge lies in parsing/converting a GET response to a POJO. Below, I have the User class and the Controller class. In the getUsers() method, I successfully parse the request using ParameterizedTypeReference with the wrapper class. However, I face di ...

Converting JSON data into a dataframe yields varying numerical values

Consider the following JSON data: $fraudster [1] FALSE $actionType [1] "LOGIN_FORM" $actionId [1] 10 $eventList [1] "[[1544018118438041139,162.0,38.0,0.023529414,1.0,2131230815,1], [1544018118466235879,162.0,38.0,0.025490198,1.0,2131230815,0], [1544018 ...

Looking at and adding to JSON files in Python

These are the contents of my two files: file1.json [ { "name": "john", "version": "0.0" }, { "name": "peter", "version": "1.0" }, { "name&qu ...

Using the Onedrive API in Python for data manipulation

I'm struggling to write a Python script that can decode JSON data retrieved from my OneDrive. I've successfully authenticated and accessed the files, but I can't figure out how to extract the file names and URLs from the JSON response. The ...

JavaScript code encounters difficulties parsing HTML source

I'm attempting to reconstruct the WhateverOrigin service, which can be found at this link: Nevertheless, when I try running it in my web browser, this code that functioned perfectly with WhateverOrigin no longer functions properly with my imitation s ...