ASP.NET Core 8:如何将EF查询的配置表数据转为指定结构JSON
问题描述
我有一张存储应用配置的SQL表,结构如下:
| Key | Value |
|---|---|
| Configurarion1 | True |
| Configurarion2 | "C:\Temp" |
我开发了一个基于ASP.NET Core 8的Web API,使用Entity Framework查询该表并返回JSON数据。目前EF默认返回的JSON结构如下:
[ { "Key": "Configurarion1", "Value": "True" }, { "Key": "Configurarion2", "Value": "C:\\Temp" } ]
但我希望得到如下符合JSON规范的结构:
[ { "Configurarion1": true, "Configurarion2": "C:\\Temp" } ]
请问是否无需复杂的workaround即可实现?以下是我的现有代码:
public class ConfigData { public string? Key{ get; set; } public string? Value { get; set; } } public class ConfigEntityDto { [Required] [MaxLength(255)] public string Key { get; set; } = ""; [MaxLength(4000)] public string Value { get; set; } = ""; } [HttpGet("/Configuration")] public async Task<ActionResult<List<ConfigData>>> ReturnConfig() { try { IQueryable<ConfigEntityDto> query = context.ConfigDb; var result = await query.ToListAsync(); if (result == null || result.Count == 0) return NoContent(); return Ok(result); } catch (Exception) { return StatusCode((int)HttpStatusCode.InternalServerError); } }
解决方案
完全可以不用复杂的workaround,只需将查询结果转换为字典并处理值类型,就能得到预期的JSON结构。
修改后的ReturnConfig方法如下:
[HttpGet("/Configuration")] public async Task<ActionResult<object[]>> ReturnConfig() { try { var configs = await context.ConfigDb.ToListAsync(); if (!configs.Any()) return NoContent(); var configDict = new Dictionary<string, object>(); foreach (var config in configs) { // 转换布尔值为JSON原生类型 if (bool.TryParse(config.Value, out bool boolVal)) { configDict[config.Key] = boolVal; } // 可选:添加数字类型转换 else if (int.TryParse(config.Value, out int intVal)) { configDict[config.Key] = intVal; } else { // 去除字符串首尾的引号(适配表中带引号的存储值) configDict[config.Key] = config.Value.Trim('"'); } } // 包裹为数组中的单个对象,匹配预期结构 return Ok(new[] { configDict }); } catch (Exception) { return StatusCode((int)HttpStatusCode.InternalServerError); } }
核心要点:
- 返回结构调整:ASP.NET Core会自动将
Dictionary<string, object>序列化为键值对形式的JSON对象,再包裹进数组即可匹配你要的结构。 - 类型转换:把数据库中存储的字符串类型布尔值(如"True")转换为JSON原生布尔类型
true,避免返回字符串形式的布尔值。 - 引号处理:针对表中带引号的路径值(如
"C:\\Temp"),通过Trim('"')去除多余引号,保证JSON值的正确性。
内容的提问来源于stack exchange,提问作者Fernando Moreno
相关产品推荐
相关产品推荐

