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

如何将Stripe Webhook的JSON请求字符串转换为ClientModelView对象?

解决JSON字符串转ClientModelView对象的问题

要把JSON字符串转换成你的模型对象,需要借助JSON序列化库来完成转换,常用的有Newtonsoft.Json(Json.NET)和.NET内置的System.Text.Json,下面分别给出两种实现方式:

方法一:使用Newtonsoft.Json(Json.NET)

  1. 先通过NuGet包管理器安装Newtonsoft.Json包
  2. 修改你的Webhook代码:
using Newtonsoft.Json;

[HttpPost]
public async Task<IHttpActionResult> Index()
{
    string result = await Request.Content.ReadAsStringAsync();
    // 配置序列化规则:忽略大小写、忽略模型不存在的字段
    var serializeSettings = new JsonSerializerSettings
    {
        PropertyNameCaseInsensitive = true,
        MissingMemberHandling = MissingMemberHandling.Ignore
    };
    ClientModelView client = JsonConvert.DeserializeObject<ClientModelView>(result, serializeSettings);
    return Ok();
}

方法二:使用System.Text.Json(.NET Core/.NET 5+内置)

如果你的项目是.NET Core或更高版本,直接用内置的序列化库即可:

using System.Text.Json;

[HttpPost]
public async Task<IHttpActionResult> Index()
{
    string result = await Request.Content.ReadAsStringAsync();
    // 配置忽略大小写,匹配JSON里的小驼峰字段
    var serializeOptions = new JsonSerializerOptions
    {
        PropertyNameCaseInsensitive = true
    };
    ClientModelView client = JsonSerializer.Deserialize<ClientModelView>(result, serializeOptions);
    return Ok();
}

必须修正的匹配问题

你当前的JSON和模型存在两个不兼容的点,不修正会导致转换失败:

  • 字段大小写不匹配:JSON里的firstName、lastName、email是小驼峰格式,而模型里是大驼峰(FirstName、LastName、Email),上面的代码已经通过PropertyNameCaseInsensitive = true配置解决了这个问题。
  • Address类型不匹配:JSON里的Address是数组(用[]包裹),但模型里Address是单个AddressModelView对象。你需要二选一调整:
    1. 修改模型:把public AddressModelView Address { get; set; }改为public List<AddressModelView> Addresses { get; set; },如果要保留JSON里的Address键名,可加特性标注[JsonPropertyName("Address")]
    2. 调整JSON结构:让Stripe发送的Address是单个对象(去掉外层的[])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 20:55:05