Home >Backend Development >C++ >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>
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>
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!