Home > Backend Development > C++ > How to Deserialize a Mixed-Type JSON Array into a Strongly Typed C# Class?

How to Deserialize a Mixed-Type JSON Array into a Strongly Typed C# Class?

Linda Hamilton
Release: 2025-01-24 04:16:07
Original
156 people have browsed it

How to Deserialize a Mixed-Type JSON Array into a Strongly Typed C# Class?

Deserialize an array of values ​​with a fixed pattern to a strongly typed data class

Deserializing JSON data with a specific structure can present challenges, especially when dealing with mixed-type arrays. Here is the complete solution on how to use JSON.NET:

1. Mixed type array and dictionary

In this case, the players collection is indeed a dictionary with usernames as keys and an array of mixed types as values.

2. Unnamed values ​​in Player

Create a custom converter that reads the array of values ​​in the correct order, matching the expected properties on the Player class:

<code>public class ObjectToArrayConverter<T> : JsonConverter
{
    // ... 省略实现细节
}</code>
Copy after login

3. Custom Player class

Apply the converter to your Player class and use JsonPropertyAttribute.Order to specify the order of the properties:

<code>[JsonConverter(typeof(ObjectToArrayConverter<Player>))]
public class Player
{
    [JsonProperty(Order = 1)]
    public int UniqueID { get; set; }
    [JsonProperty(Order = 2)]
    public string PlayerDescription { get; set; }
    // ... 其他字段(根据需要)
}</code>
Copy after login

4. Root object

Create a strongly typed root object containing a dictionary of players:

<code>public class ScoreboardResults
{
    public int timestamp { get; set; }
    public int total_players { get; set; }
    public int max_score { get; set; }
    public Dictionary<string, Player> players { get; set; }
}</code>
Copy after login

5. Deserialize using Newtonsoft

<code>var results = JsonConvert.DeserializeObject<ScoreboardResults>(json);</code>
Copy after login

Demonstration example:

This revised response maintains the image and its format while rewording the text for improved clarity and flow. The code blocks remain unchanged, as they are crucial to the article's content. The key changes are in sentence structure and word choice to achieve a pseudo-original version.

The above is the detailed content of How to Deserialize a Mixed-Type JSON Array into a Strongly Typed C# Class?. 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