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

C#反序列化无结果求助:含Result嵌套的JSON解析失败

JSON反序列化失败问题解决方法

问题根源

你的JSON结构外层包含Result属性,其值才是目标HotelRoomDTO数组,但代码中直接将整个JSON字符串反序列化为IEnumerable<HotelRoomDTO>,结构不匹配导致反序列化失败。

解决方案

方案1:创建匹配JSON结构的根对象类

定义一个根类对应外层JSON结构,再从中提取目标数组:

// 新增根对象类
public class HotelRoomResponse
{
    public IEnumerable<HotelRoomDTO> Result { get; set; }
}

// 修改服务代码中的反序列化逻辑
public async Task<IEnumerable<HotelRoomDTO>> GetHotelRooms(string checkInDate, string checkOutDate)
{
    var settings = new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore,
        MissingMemberHandling = MissingMemberHandling.Ignore
    };
    var response = await _client.GetAsync($"api/hotelroom?checkInDate={checkInDate}&checkOutDate={checkOutDate}");
    var content = await response.Content.ReadAsStringAsync();
    // 先反序列化到根对象
    var responseObj = JsonConvert.DeserializeObject<HotelRoomResponse>(content, settings);
    // 返回Result中的数组
    return responseObj?.Result ?? Enumerable.Empty<HotelRoomDTO>();
}

方案2:直接解析JSON提取目标数组(无需新增类)

使用Newtonsoft.Json的JObject直接解析并提取Result部分:

public async Task<IEnumerable<HotelRoomDTO>> GetHotelRooms(string checkInDate, string checkOutDate)
{
    var settings = new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore,
        MissingMemberHandling = MissingMemberHandling.Ignore
    };
    var response = await _client.GetAsync($"api/hotelroom?checkInDate={checkInDate}&checkOutDate={checkOutDate}");
    var content = await response.Content.ReadAsStringAsync();
    // 解析JSON对象
    var jsonObj = JObject.Parse(content);
    // 提取Result数组并反序列化
    var rooms = jsonObj["Result"].ToObject<IEnumerable<HotelRoomDTO>>(JsonSerializer.Create(settings));
    return rooms ?? Enumerable.Empty<HotelRoomDTO>();
}

额外注意事项

你的示例JSON中每个对象最后一个属性后存在多余逗号(比如"Name": "LL Bottom Bracket",末尾的逗号),部分JSON解析器会因此报错,建议移除这类尾随逗号,避免额外解析问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 18:32:29