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

如何拆分StreamReader响应流并解析为Customer对象数组/集合

问题核心

接口返回的内容为JSON数组(外层用[]包裹多个对象结构),而你使用的JObject.Parse()仅支持解析单个JSON对象(外层用{}包裹),因此触发解析异常。

修复方案

提供两种常用实现方式,可按需选择:

方案1:JArray解析后手动映射

适合需要自定义字段转换逻辑的场景:

using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.IO;
using System.Net;

public IEnumerable<Customer> GetByPage(int page)
{
    List<Customer> customers = new List<Customer>();
    try
    {
        WebRequest request = WebRequest.Create($"http://localhost:5002/api/customer/GetByPage?page={page}");
        using (WebResponse response = request.GetResponse())
        using (StreamReader stream = new StreamReader(response.GetResponseStream()))
        {
            string incomingStream = stream.ReadToEnd();
            // 改用JArray解析JSON数组
            JArray jsonArray = JArray.Parse(incomingStream);
            
            // 遍历数组生成Customer对象
            foreach (JObject item in jsonArray)
            {
                Customer customer = new Customer();
                customer.Id = item.Value<int>("id");
                customer.TitleId = item.Value<int>("titleId");
                customer.FirstName = item.Value<string>("firstName");
                // 其余字段赋值逻辑同理
                customers.Add(customer);
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
    return customers;
}

注意:原代码中TitleId赋值错误取用了id字段的值,上述代码已修正为对应titleId字段。

方案2:直接反序列化(更简洁)

只要保证Customer类的属性和JSON返回的字段名匹配,可直接一步转换,无需手动逐个赋值:

using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Net;

public IEnumerable<Customer> GetByPage(int page)
{
    try
    {
        WebRequest request = WebRequest.Create($"http://localhost:5002/api/customer/GetByPage?page={page}");
        using (WebResponse response = request.GetResponse())
        using (StreamReader stream = new StreamReader(response.GetResponseStream()))
        {
            string incomingStream = stream.ReadToEnd();
            // 直接反序列化为Customer集合
            return JsonConvert.DeserializeObject<List<Customer>>(incomingStream);
        }
    }
    catch (Exception)
    {
        throw;
    }
}

如果属性名和JSON字段名不一致,可在Customer类的对应属性上添加[JsonProperty("JSON字段名")]特性做映射。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 23:36:04