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

.NET 6 WebAPI如何接收通用JSON数组作为输入

.NET 6 WebAPI 接收通用JSON数组解决方案

a) 请求Body的输入数据类型

在System.Text.Json体系下,替代JSON.NET JArray的首选类型是**JsonElement[]**(或List<JsonElement>),也可以直接用JsonDocument接收整个JSON数组(JsonDocument可表示任意JSON结构,包括数组)。

  • 使用JsonElement[]时,WebAPI会自动完成请求Body到该类型的反序列化,无需额外配置:
[HttpPost("upload-array")]
public IActionResult ReceiveJsonArray([FromBody] JsonElement[] jsonArray)
{
    // 处理数组逻辑
    return Ok();
}
  • 使用JsonDocument时,需注意释放资源(用using包裹或手动调用Dispose()),同时可先校验根节点是否为数组:
[HttpPost("upload-document")]
public IActionResult ReceiveJsonDocument([FromBody] JsonDocument jsonDoc)
{
    if (jsonDoc.RootElement.ValueKind != JsonValueKind.Array)
    {
        return BadRequest("输入不是JSON数组");
    }
    // 遍历数组元素
    foreach (var element in jsonDoc.RootElement.EnumerateArray())
    {
        // 处理单个元素逻辑
    }
    jsonDoc.Dispose();
    return Ok();
}

b) 读取数组并转换为通用JSON对象

.NET 6的System.Text.Json中没有直接的JsonObject类型(该类型在.NET 7引入),通用JSON对象可通过**JsonElement**表示(它能承载任意JSON值:对象、数组、字符串等)。

方法1:直接遍历接收的JsonElement[]

接收数组后,直接遍历每个JsonElement,通过其内置方法操作属性:

foreach (var jsonObj in jsonArray)
{
    if (jsonObj.ValueKind == JsonValueKind.Object)
    {
        // 枚举所有属性
        foreach (var property in jsonObj.EnumerateObject())
        {
            string propName = property.Name;
            JsonElement propValue = property.Value;
            
            // 根据值类型提取数据
            if (propValue.ValueKind == JsonValueKind.String)
            {
                string strValue = propValue.GetString();
            }
            else if (propValue.ValueKind == JsonValueKind.Number)
            {
                int intValue = propValue.GetInt32();
            }
        }
    }
}

方法2:从请求流手动解析

若需要底层控制,可直接读取请求流并解析:

[HttpPost("upload-stream")]
public async Task<IActionResult> ReceiveFromStream()
{
    using var streamReader = new StreamReader(Request.Body);
    string jsonContent = await streamReader.ReadToEndAsync();
    using var jsonDoc = JsonDocument.Parse(jsonContent);
    
    if (jsonDoc.RootElement.ValueKind != JsonValueKind.Array)
    {
        return BadRequest("输入不是JSON数组");
    }
    
    foreach (var element in jsonDoc.RootElement.EnumerateArray())
    {
        // 处理单个JsonElement
    }
    
    return Ok();
}

NDJSON方案

若采用NDJSON(每行一个独立JSON对象),可逐行读取请求流并解析:

[HttpPost("upload-ndjson")]
public async Task<IActionResult> ReceiveNDJSON()
{
    using var streamReader = new StreamReader(Request.Body);
    string line;
    while ((line = await streamReader.ReadLineAsync()) != null)
    {
        if (string.IsNullOrWhiteSpace(line)) continue;
        
        using var jsonDoc = JsonDocument.Parse(line);
        JsonElement jsonObj = jsonDoc.RootElement;
        // 处理单个JSON对象逻辑
    }
    
    return Ok();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:20:29