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

如何在C# Web API中返回嵌套列表格式的JSON响应?

你当前代码的问题出在两处:

  1. DispatchData类的data字段定义为一维字符串数组string[],无法存储多个子数组结构
  2. 遍历查询结果的循环中,每次都给dta.data重新赋值,只会保留最后一条记录的内容

第一步:修改DispatchData类定义

把data字段修改为List<string[]>类型(Json.NET序列化时会自动转为JSON数组,完全符合你要的输出格式):

public class DispatchData
{
    public List<string[]> data = new List<string[]>();
}

第二步:修改业务逻辑代码

循环中改为往data列表添加子数组,不要覆盖整个字段:

DispatchData dta = new DispatchData();
using (SalesDataContext oSqlData4 = new SalesDataContext())
{
    // amount paid -- not paid
    var Amount_Paid = (from x in oSqlData4.Finances
                       where 
                       (x.Order.Customer_ID.Equals("190") ||
                        x.Order.Customer_ID.Equals("1334"))
                       where (x.Status == "Not Approved")
                       select x).ToList();
    foreach (var item in Amount_Paid)
    {
        dta.data.Add(new string[] { item.Order_ID.ToString(), item.ID.ToString() });
    }
    var json = JsonConvert.SerializeObject(dta);
    return json;
}

输出效果验证

修改后序列化得到的JSON就是你需要的嵌套数组格式:

{"data":[ ["2508","4684"],["2508","4684"],....] }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:27:03