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

Mpesa API反序列化报错:access_token未定义等问题求助

解决Mpesa API响应反序列化获取access_token的问题

问题排查与修复步骤

1. 确保TokenResponse类与JSON字段严格匹配

Mpesa API返回的标准JSON结构如下:

{
  "access_token": "your_token_value",
  "expires_in": 3599
}

反序列化失败的核心原因通常是类属性与JSON字段不匹配(默认序列化器区分大小写),需通过特性显式绑定:

Newtonsoft.Json 适配类示例:

public class TokenResponse
{
    [JsonProperty("access_token")]
    public string AccessToken { get; set; }

    [JsonProperty("expires_in")]
    public int ExpiresIn { get; set; }
}

System.Text.Json 适配类示例:

public class TokenResponse
{
    [JsonPropertyName("access_token")]
    public string AccessToken { get; set; }

    [JsonPropertyName("expires_in")]
    public int ExpiresIn { get; set; }
}

2. 修正反序列化代码逻辑

反序列化后必须先判空,再访问属性,避免空引用异常:

Newtonsoft.Json 反序列化示例:

var rawJson = await httpResponse.Content.ReadAsStringAsync();
var tokenResult = JsonConvert.DeserializeObject<TokenResponse>(rawJson);

if (tokenResult != null && !string.IsNullOrEmpty(tokenResult.AccessToken))
{
    var accessToken = tokenResult.AccessToken;
    // 后续业务逻辑
}
else
{
    // 打印原始JSON排查问题
    Console.WriteLine($"API原始响应: {rawJson}");
}

System.Text.Json 反序列化示例:

var rawJson = await httpResponse.Content.ReadAsStringAsync();
var tokenResult = JsonSerializer.Deserialize<TokenResponse>(rawJson);

if (tokenResult != null && !string.IsNullOrEmpty(tokenResult.AccessToken))
{
    var accessToken = tokenResult.AccessToken;
    // 后续业务逻辑
}
else
{
    Console.WriteLine($"API原始响应: {rawJson}");
}

3. 验证API实际返回内容

如果仍报错,打印API返回的原始JSON,确认是否包含access_token和expires_in字段。若返回的是错误结构(如下方示例),需先解决请求认证问题:

{
  "error": "invalid_credentials",
  "error_description": "Invalid consumer key or secret"
}

4. 避免空引用异常

注释类属性后触发NullReferenceException,是因为你直接访问了反序列化后的null对象属性。必须在代码中增加非空判断,确保对象有效后再读取属性。

内容的提问来源于stack exchange,提问作者The Only Smart Boy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 17:15:57