You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中使用IParseNode将JSON数组反序列化为对象列表?

问题描述

我正在使用Microsoft Graph API及Kiota生成的模型,已成功通过以下代码将单个Participant实体从JSON反序列化:

IParseNode parseNode = new JsonParseNode(jsonString);
var participant = new Participant();
var fieldDeserializers = participant.GetFieldDeserializers();

foreach (var field in fieldDeserializers)
{
    var propertyParseNode = parseNode.GetChildNode(field.Key);
    if (propertyParseNode != null)
    {
        field.Value(propertyParseNode);
    }
}

但我需要将JSON数组反序列化为List<Participant>,不确定如何修改代码来遍历数组并正确反序列化每个Participant对象。

我已尝试的代码:

var participantsNode = parseNode.GetChildNode("participants");

foreach (var childNode in participantsNode.GetChildNode()) //IParseNode没有这个属性
解决方案

要处理Participant数组的反序列化,Kiota的IParseNode提供了专门的集合处理能力,你可以通过以下两种方式实现:

方法1:使用Kiota内置集合反序列化方法

直接调用GetCollectionOfObjectValues方法,它会自动遍历数组并完成每个对象的反序列化,代码更简洁:

IParseNode parseNode = new JsonParseNode(jsonString);
// 获取对应数组字段的节点
var participantsNode = parseNode.GetChildNode("participants");
// 直接反序列化为List<Participant>
List<Participant> participants = participantsNode.GetCollectionOfObjectValues<Participant>(() => new Participant()).ToList();

方法2:手动遍历数组节点

如果需要保持手动处理的逻辑,可以通过GetChildren方法获取数组的所有子节点,再逐个反序列化:

IParseNode parseNode = new JsonParseNode(jsonString);
var participantsNode = parseNode.GetChildNode("participants");
List<Participant> participants = new();

// 遍历数组中的每个元素节点
foreach (var childNode in participantsNode.GetChildren())
{
    var participant = new Participant();
    var fieldDeserializers = participant.GetFieldDeserializers();
    
    foreach (var field in fieldDeserializers)
    {
        var propertyNode = childNode.GetChildNode(field.Key);
        if (propertyNode != null)
        {
            field.Value(propertyNode);
        }
    }
    
    participants.Add(participant);
}

补充说明

  • 如果你的JSON根节点本身就是Participant数组(而非嵌套在"participants"字段下),直接在根parseNode上调用GetCollectionOfObjectValues即可,无需先获取子节点。
  • 优先推荐方法1,Kiota内置方法已经封装了错误处理和通用逻辑,减少手动代码的出错概率。

内容的提问来源于stack exchange,提问作者Shad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 18:07:20