C# Azure函数中基于半已知结构JSON创建DataTable
嘿,我来帮你搞定这个C# Azure函数处理动态JSON的问题!针对你说的场景——固定字段加上动态结构的列表项,我们可以用两种主流的JSON处理方式来实现,具体看你项目用的是哪个库:
解决方案:处理Azure函数中的动态JSON结构
方案一:使用Newtonsoft.Json(多数Azure函数默认依赖)
这种方式用JObject来承载未知结构的business_key,非常灵活:
1. 定义基础模型类
先把固定字段的模型写好,动态部分用JObject来接收:
using Newtonsoft.Json.Linq; public class DynamicRequestModel { public int ssid { get; set; } public int dim { get; set; } public int type { get; set; } public List<BusinessKeyContainer> list_of_business_keys { get; set; } } public class BusinessKeyContainer { // 用JObject接收未知列名和类型的business_key public JObject business_key { get; set; } }
2. 在Azure函数中处理请求
在HTTP触发的函数里,反序列化后就能同时访问固定字段和遍历动态内容:
using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.IO; using System.Threading.Tasks; [FunctionName("ProcessDynamicBusinessKeys")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("开始处理动态JSON请求"); // 读取请求体 string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); try { // 反序列化为定义好的模型 var requestModel = JsonConvert.DeserializeObject<DynamicRequestModel>(requestBody); // 访问固定字段 log.LogInformation($"ssid: {requestModel.ssid}, dim: {requestModel.dim}, type: {requestModel.type}"); // 遍历每个business_key的动态字段 foreach (var keyItem in requestModel.list_of_business_keys) { foreach (JProperty prop in keyItem.business_key.Properties()) { log.LogInformation($"列名: {prop.Name}, 值: {prop.Value}, 数据类型: {prop.Value.Type}"); // 按需转换类型,比如转int、string等 if (prop.Value.Type == JTokenType.Integer) { int intValue = prop.Value.Value<int>(); // 做你需要的业务处理 } } } return new OkObjectResult("请求处理完成"); } catch (JsonException ex) { log.LogError($"JSON格式错误: {ex.Message}"); return new BadRequestObjectResult("无效的JSON格式"); } }
方案二:使用System.Text.Json(.NET Core原生库)
如果你的项目用的是原生JSON序列化库,可以用JsonElement来处理动态结构:
1. 定义基础模型类
动态部分用JsonElement承载:
using System.Text.Json; public class DynamicRequestModel { public int ssid { get; set; } public int dim { get; set; } public int type { get; set; } public List<BusinessKeyContainer> list_of_business_keys { get; set; } } public class BusinessKeyContainer { public JsonElement business_key { get; set; } }
2. 在Azure函数中处理请求
反序列化后遍历动态字段:
using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System.Text.Json; using System.Threading.Tasks; [FunctionName("ProcessDynamicBusinessKeys")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("开始用System.Text.Json处理动态JSON请求"); try { // 直接从请求体反序列化 var requestModel = await JsonSerializer.DeserializeAsync<DynamicRequestModel>(req.Body); // 访问固定字段 log.LogInformation($"ssid: {requestModel.ssid}, dim: {requestModel.dim}, type: {requestModel.type}"); // 遍历动态business_key foreach (var keyItem in requestModel.list_of_business_keys) { if (keyItem.business_key.ValueKind == JsonValueKind.Object) { foreach (var prop in keyItem.business_key.EnumerateObject()) { log.LogInformation($"列名: {prop.Name}, 值: {prop.Value}, 数据类型: {prop.Value.ValueKind}"); // 按需转换类型,比如转int、string if (prop.Value.ValueKind == JsonValueKind.Number) { int intValue = prop.Value.GetInt32(); // 业务处理逻辑 } } } } return new OkObjectResult("请求处理完成"); } catch (JsonException ex) { log.LogError($"JSON格式错误: {ex.Message}"); return new BadRequestObjectResult("无效的JSON格式"); } }
额外小技巧
如果需要把动态的business_key转换成字典方便操作,可以这样做:
- Newtonsoft.Json:
var keyDict = keyItem.business_key.ToObject<Dictionary<string, object>>(); - System.Text.Json:
var keyDict = JsonSerializer.Deserialize<Dictionary<string, object>>(keyItem.business_key.GetRawText());
这样就能灵活处理那些未知的列名和数据类型啦,根据你的项目依赖选择对应的方案就行~
内容的提问来源于stack exchange,提问作者Jangcy
相关产品推荐
相关产品推荐

