Home > Backend Development > C++ > How to Deserialize JSON with Numerically-Named Keys in C#?

How to Deserialize JSON with Numerically-Named Keys in C#?

Linda Hamilton
Release: 2025-02-02 12:26:10
Original
601 people have browsed it

How to Deserialize JSON with Numerically-Named Keys in C#?

Handling JSON with Invalid C# Class Names

The Newtonsoft JSON library can struggle with JSON containing keys that violate C# naming conventions (like keys starting with numbers). Let's examine how to handle JSON like this:

<code class="language-json">{
  "1": {
    "fajr": "04:15",
    "sunrise": "05:42",
    "zuhr": "12:30",
    "asr": "15:53",
    "maghrib": "19:18",
    "isha": "20:40"
  },
  "2": {
    "fajr": "04:15",
    "sunrise": "05:42",
    "zuhr": "12:30",
    "asr": "15:53",
    "maghrib": "19:18",
    "isha": "20:41"
  }
}</code>
Copy after login

Since C# class names can't begin with a number, a direct deserialization won't work. The solution is to deserialize into a dictionary.

Deserialization to a Dictionary

This approach uses a dictionary to store the data, where keys are the numerical identifiers from the JSON and values are C# objects representing the prayer times.

<code class="language-csharp">public class PrayerTimes
{
    public string fajr { get; set; }
    public string sunrise { get; set; }
    public string zuhr { get; set; }
    public string asr { get; set; }
    public string maghrib { get; set; }
    public string isha { get; set; }
}

// ... later in your code ...

string json = @"{""1"":{""fajr"":""04:15"",""sunrise"":""05:42"",""zuhr"":""12:30"",""asr"":""15:53"",""maghrib"":""19:18"",""isha"":""20:40""},""2"":{""fajr"":""04:15"",""sunrise"":""05:42"",""zuhr"":""12:30"",""asr"":""15:53"",""maghrib"":""19:18"",""isha"":""20:41""}}";

var prayerTimesDictionary = JsonConvert.DeserializeObject<Dictionary<string, PrayerTimes>>(json);

// Accessing the data:
foreach (var kvp in prayerTimesDictionary)
{
    Console.WriteLine($"Day {kvp.Key}: Fajr - {kvp.Value.fajr}");
    // Access other prayer times similarly...
}</code>
Copy after login

This code defines a PrayerTimes class and then uses JsonConvert.DeserializeObject to parse the JSON into a dictionary where keys are strings (representing the day numbers) and values are PrayerTimes objects. This effectively bypasses the C# naming restrictions.

The above is the detailed content of How to Deserialize JSON with Numerically-Named Keys in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template