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

如何使用CreateFromDiscriminatorValue?Teams Webhook反序列化咨询

处理Teams Webhook通知的反序列化问题

关于ChangeNotificationCollectionResponse类型的确认

Teams通过Webhook推送的变更通知 payload,确实对应ChangeNotificationCollectionResponse类型,它是Microsoft Graph SDK中用于封装批量变更通知的容器。

两种反序列化方式

1. 使用SDK自带的CreateFromDiscriminatorValue方法

这个方法是SDK专门设计来处理多态类型反序列化的,完全可以使用。它会自动识别payload中的@odata.type字段,匹配对应的具体通知类型,比常规JSON工具更适配Graph的结构。

示例代码(C#为例):

using Microsoft.Graph.Models;
using System.Text.Json;

// 假设webhook接收的原始JSON字符串为webhookPayload
var jsonElement = JsonDocument.Parse(webhookPayload).RootElement;
var notificationCollection = ChangeNotificationCollectionResponse.CreateFromDiscriminatorValue(jsonElement);

// 遍历处理每个通知
foreach (var notification in notificationCollection.Value)
{
    // 根据通知类型做针对性处理,比如判断是否为聊天消息通知
    if (notification is ChatMessageChangeNotification chatNotification)
    {
        var messageId = chatNotification.ResourceData.Id;
        // 这里添加你的业务处理逻辑
    }
}

2. 使用常规JSON反序列化工具

如果不想依赖SDK方法,也可以直接用System.Text.Json或Newtonsoft.Json这类工具,但需要注意两点:

  • 确保自定义模型的字段和payload完全匹配,包括Graph特有的字段(比如@odata.type、resourceData等)
  • 对于多态的通知类型,需要手动识别处理

示例代码(System.Text.Json):

using System.Text.Json;
using System.Text.Json.Serialization;

// 自定义对应模型(参考SDK的ChangeNotificationCollectionResponse结构)
public class CustomNotificationCollection
{
    public List<CustomChangeNotification> Value { get; set; }
}

public class CustomChangeNotification
{
    [JsonPropertyName("@odata.type")]
    public string ODataType { get; set; }
    public CustomResourceData ResourceData { get; set; }
    // 按需添加其他字段,比如subscriptionId、clientState等
}

public class CustomResourceData
{
    [JsonPropertyName("@odata.type")]
    public string ODataType { get; set; }
    public string Id { get; set; }
    // 按需添加资源相关字段
}

// 执行反序列化
var options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true,
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var collection = JsonSerializer.Deserialize<CustomNotificationCollection>(webhookPayload, options);

注意事项

  • 优先推荐使用SDK的CreateFromDiscriminatorValue方法,它已经封装了Graph类型的多态处理逻辑,能减少手动适配的错误
  • 如果使用自定义模型,要通过JsonPropertyName特性标注Graph特有的字段名,避免序列化失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:39:59