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

.NET 7.0中使用Refit调用API遇JsonCollectionConverter空响应异常求助

解决方案:Refit处理空响应({}转空数组)异常

方法1:自定义JSON转换器处理对象转空数组

创建一个自定义JSON转换器,当遇到JSON对象({})时直接返回空列表,规避解析异常:

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

public class EmptyObjectToListConverter<T> : JsonConverter<List<T>>
{
    public override List<T>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.StartObject)
        {
            reader.Skip();
            return new List<T>();
        }
        return JsonSerializer.Deserialize<List<T>>(ref reader, options);
    }

    public override void Write(Utf8JsonWriter writer, List<T> value, JsonSerializerOptions options)
    {
        JsonSerializer.Serialize(writer, value, options);
    }
}

将转换器注册到Refit的序列化配置中:

var refitSettings = new RefitSettings
{
    ContentSerializer = new SystemTextJsonContentSerializer(new JsonSerializerOptions
    {
        Converters = { new EmptyObjectToListConverter<YourModelType>() }
        // 可添加其他序列化配置,如忽略null、驼峰命名等
    })
};

var apiClient = RestService.For<IApiInterface>("https://your-api-url", refitSettings);

方法2:调整API返回格式(若有权限)

如果能控制API端逻辑,让空数据场景返回**空数组[]**而非空对象{},直接适配Refit默认的数组解析逻辑,无需修改客户端代码。

方法3:手动处理原始响应

用Refit的ApiResponse<T>包装返回结果,手动判断并处理空对象响应:

public interface IApiInterface
{
    [Get("/api/data")]
    Task<ApiResponse<List<YourModelType>>> GetDataAsync();
}

// 调用时处理响应
var response = await apiClient.GetDataAsync();
if (response.IsSuccessStatusCode)
{
    List<YourModelType> result;
    if (string.IsNullOrWhiteSpace(response.Content) || response.Content == "{}")
    {
        result = new List<YourModelType>();
    }
    else
    {
        result = JsonSerializer.Deserialize<List<YourModelType>>(response.Content, new JsonSerializerOptions());
    }
    // 业务逻辑处理
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 12:33:18