Home >Backend Development >C++ >How to Deserialize a JSON Array of Mixed-Type Values into Strongly Typed C# Objects?
When dealing with JSON data with a specific schema, deserializing it into strongly typed data classes can improve code maintainability and clarity. This question explores how to deserialize such data when the array contains mixed type values, specifically integers and strings.
There are two key factors to consider when deserializing this type of data:
To solve these problems, we can implement a custom deserialization converter. This converter is implemented in C#, utilizing the ObjectToArrayConverter<T>
class in Newtonsoft.Json:
<code class="language-csharp">public class ObjectToArrayConverter<T> : JsonConverter { // ... (为简洁起见,省略实现细节) }</code>
Next, we define the Player class and use annotated properties to specify the order in which it is deserialized:
<code class="language-csharp">[JsonConverter(typeof(ObjectToArrayConverter<Player>))] public class Player { [JsonProperty(Order = 1)] public int UniqueID { get; set; } [JsonProperty(Order = 2)] public string PlayerDescription { get; set; } // ... (根据需要添加其他属性) }</code>
Finally, the top-level ScoreboardResults
class should be adjusted to represent player data as a dictionary with usernames as keys:
<code class="language-csharp">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>
Using custom converters and annotated properties, we can now deserialize JSON data into strongly typed objects:
<code class="language-json">{ "timestamp": 1473730993, "total_players": 945, "max_score": 8961474, "players": { "Player1Username": [ 121, "somestring", 679900, 5, 4497, "anotherString", "thirdString", "fourthString", 123, 22, "YetAnotherString"], "Player2Username": [ 886, "stillAstring", 1677, 1, 9876, "alwaysAstring", "thirdString", "fourthString", 876, 77, "string"] } }</code>The
result will be a filled ScoreboardResults
object containing a dictionary of Player
objects, each containing the expected values in their respective properties.
This revised output maintains the original image and provides a more concise and technically accurate explanation of the JSON deserialization process. The code examples are also improved for clarity.
The above is the detailed content of How to Deserialize a JSON Array of Mixed-Type Values into Strongly Typed C# Objects?. For more information, please follow other related articles on the PHP Chinese website!