首页 > 后端开发 > C++ > 如何将混合类型 JSON 数组反序列化为强类型 C# 类?

如何将混合类型 JSON 数组反序列化为强类型 C# 类?

Linda Hamilton
发布: 2025-01-24 04:16:07
原创
196 人浏览过

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

将具有固定模式的值数组反序列化到强类型数据类

反序列化具有特定结构的 JSON 数据可能会带来挑战,尤其是在处理混合类型数组时。以下是如何使用 JSON.NET 的完整解决方案:

1. 混合类型数组和字典

在本例中,玩家集合确实是一个字典,用户名作为键,混合类型的数组作为值。

2. Player 中未命名的值

创建一个自定义转换器,按正确的顺序读取值数组,匹配 Player 类上的预期属性:

<code>public class ObjectToArrayConverter<T> : JsonConverter
{
    // ... 省略实现细节
}</code>
登录后复制

3. 自定义 Player 类

将转换器应用于您的 Player 类,并使用 JsonPropertyAttribute.Order 指定属性的顺序:

<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>
登录后复制

4. 根对象

创建一个包含玩家字典的强类型根对象:

<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>
登录后复制

5. 使用 Newtonsoft 反序列化

<code>var results = JsonConvert.DeserializeObject<ScoreboardResults>(json);</code>
登录后复制

演示示例:

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.

以上是如何将混合类型 JSON 数组反序列化为强类型 C# 类?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板