Home > Backend Development > C++ > How to Deserialize JSON with Illegal C# Identifiers?

How to Deserialize JSON with Illegal C# Identifiers?

Linda Hamilton
Release: 2025-02-02 12:16:11
Original
974 people have browsed it

How to Deserialize JSON with Illegal C# Identifiers?

Treatment JSON back serialization with an invalid C#identifier

When the values ​​of the C#identifier cannot be converted to the valid C#identifier in the counter -serialized JSON string, some alternative methods can be considered.

Use the dictionary

In order to deal with this situation, you can consider turning the JSON string into a dictionary instead of class. Dictionary allows the use of string as a key to provide a flexible way to access the data, even if the identifier is invalid.

The following is an example of handling this situation with dictionary:

For the JSON string in the problem:
<code class="language-csharp">public class Item
{
    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; }
}

// 将JSON字符串反序列化为字典
var dict = JsonConvert.DeserializeObject<Dictionary<string, Item>>(json);</code>
Copy after login

You can use the string key ("1" and "2") to access the data in the dictionary, for example:
<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

The above is the detailed content of How to Deserialize JSON with Illegal C# Identifiers?. 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