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

如何在C#(Azure Function)中从SQL行生成JSON数组

解决Azure Function从Azure SQL生成指定JSON数组的问题

1. 定义匹配JSON结构的实体类

根据你期望的嵌套JSON格式,先创建对应的C#类来映射数据:

// 对应外层的分类对象
public class CategoryItem
{
    public string Category { get; set; }
    public List<Item> Items { get; set; }
}

// 对应分类下的子项
public class Item
{
    public string ItemName { get; set; }
    public decimal Price { get; set; }
    // 按需添加SQL结果中的其他字段,比如Description、ImageUrl等
}

2. 实现数据读取与分组逻辑

替换你原有的Serialize方法,编写自定义方法将SqlDataReader中的数据转换为嵌套结构:

private List<CategoryItem> ConvertDataReaderToNestedItems(SqlDataReader reader)
{
    // 用字典按Category分组,避免重复创建分类对象
    var categoryDict = new Dictionary<string, CategoryItem>();

    while (reader.Read())
    {
        // 读取SQL列的值,替换成你实际的列名
        string category = reader.GetString(reader.GetOrdinal("Category"));
        string itemName = reader.GetString(reader.GetOrdinal("ItemName"));
        decimal price = reader.GetDecimal(reader.GetOrdinal("Price"));

        // 若分类不存在,先创建新的分类对象
        if (!categoryDict.ContainsKey(category))
        {
            categoryDict[category] = new CategoryItem
            {
                Category = category,
                Items = new List<Item>()
            };
        }

        // 向分类的Items列表添加子项
        categoryDict[category].Items.Add(new Item
        {
            ItemName = itemName,
            Price = price
            // 为其他字段赋值,比如 Description = reader.GetString(reader.GetOrdinal("Description"))
        });
    }

    // 将字典值转换为列表,得到最终嵌套结构
    return categoryDict.Values.ToList();
}

3. 修改Azure Function中的调用代码

把原来的Serialize(dataReader)调用替换为上面的自定义方法:

await connection.OpenAsync();
SqlDataReader dataReader = await command.ExecuteReaderAsync();

var nestedItems = ConvertDataReaderToNestedItems(dataReader);
json = JsonConvert.SerializeObject(nestedItems, Formatting.Indented);

关键注意事项

  • 处理NULL值:如果SQL列可能为空,读取时要先判断,避免报错:
    string description = reader.IsDBNull(reader.GetOrdinal("Description")) 
        ? null 
        : reader.GetString(reader.GetOrdinal("Description"));
    
  • NuGet依赖:确保项目已安装Newtonsoft.Json包(因用到JsonConvert),可通过NuGet管理器安装。
  • 列名匹配:GetOrdinal中的字符串必须与SQL查询返回的列名完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:40:29