Deserialize an array of values with a fixed pattern to a strongly typed data class
Question:
There are challenges when deserializing JSON data in a specific format into strongly typed data classes. The data contains an array of players with mixed string and integer values, and the player class consists entirely of unnamed values, in a fixed order.
Solution:
A combination of custom converters and data contract attributes allows efficient deserialization:
Create a custom converter:
Implement a custom converter that converts objects to arrays:
<code class="language-c#">public class ObjectToArrayConverter<T> : JsonConverter { // 实现 WriteJson 和 ReadJson 函数 }</code>
Apply custom converter and data contract properties to Player:
Apply a custom converter to the Player class and use the data contract attribute to specify the order of its properties:
<code class="language-c#">[JsonConverter(typeof(ObjectToArrayConverter<Player>))] [DataContract] public class Player { [DataMember(Order = 1)] public int UniqueID { get; set; } [DataMember(Order = 2)] public string PlayerDescription { get; set; } }</code>
Modify the root object to a dictionary:
Change the type of the players attribute in the root object to a dictionary, using player usernames as keys:
<code class="language-c#">public class ScoreboardResults { // ... public Dictionary<string, Player> players { get; set; } }</code>
Example:
The following code example demonstrates deserialization using this solution:
<code class="language-c#">using Newtonsoft.Json; var json = "{...}"; var results = JsonConvert.DeserializeObject<ScoreboardResults>(json);</code>
Other instructions:
The above is the detailed content of How to Deserialize a JSON Array of Mixed-Type Values into Strongly Typed C# Data Classes?. For more information, please follow other related articles on the PHP Chinese website!