所以我目前正在用 .net5 构建一个 ASP.NET WEB API(我在一家公司实习,不幸的是我们只有 .net5 应用程序)。
简而言之,我的数据库中有一个“Component”表,其中包含一个 JSON 属性“Details”,EF Core 将其作为字符串导入到我的模型中。这没问题,我在我的模型中创建了另一个属性,ComponentDTO
用于将字符串解析为实际的 JSON 值。
public partial class Component
{
[...]
public string Details { get; set; }
[...]
}
public class ComponentDTO
{
[...]
public string Details { get; set; }
public JObject ParsedDetails { get; set; }
}
我知道它以正确的方式解析,因为我捕获了应该在我的 API 函数内发送的 JSON,如下所示(电路板有组件):
[HttpGet("{Ref}")]
public async Task<ActionResult<IEnumerable<Board>>> Get(string Ref)
{
try
{
var board = await _boardService.GetOneBoard(Ref);
if (board == null)
{
return NotFound();
}
Console.WriteLine(board.Compositions.ElementAt(3).Component.ParsedDetails);
var responseBody = JsonConvert.SerializeObject(board, Formatting.Indented);
_logger.LogInformation($"Response: {responseBody}");
return Ok(board);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
return StatusCode(500, "Internal Server Error");
}
}
因此,当我记录响应主体时,我得到的是一个组件的详细信息:
"ParsedDetails": {
"core": "Cortex-A53",
"speed": "1.2 GHz",
"memory_interface": "DDR3/4"
}
但在 Swagger 或我的浏览器中,这是我对同一组件获得的结果:
"parsedDetails": {
"core": [],
"speed": [],
"memory_interface": []
}
这是我解析 JSON 属性的方式:
public static JObject ParseJsonDetails(string jsonString)
{
JObject parsedDetails = string.IsNullOrEmpty(jsonString) ? new JObject() : JObject.Parse(jsonString);
Console.WriteLine(parsedDetails);
return parsedDetails;
}
public async Task<BoardDTO> GetOneBoard(string reference)
{
return await _context.Boards
.Select(b => new BoardDTO
{
[...]
Compositions = b.Compositions.Select(c => new CompositionDTO
{
Component = new ComponentDTO
{
[...]
ParsedDetails = ParseJsonDetails(c.Component.Details),
}
}).ToList(),
[...]
})
.FirstOrDefaultAsync(b => b.Ref == reference);
}
我实际上不知道该怎么做,因为我在发送响应主体之前就捕获了它,而且我不知道该Ok(board)
值是如何处理的,也没有引发任何异常或错误。
默认情况下,.NET (Core) Web API 使用来自System.Text.Json的 JSON 序列化器。相信它无法处理
JObject
来自 Newtonsoft.Json (不同的 JSON 序列化器库) 的类。您需要从 NuGet安装Microsoft.AspNetCore.Mvc.NewtonsoftJson包
并在
Startup.ConfigureServices
参考:添加基于Newtonsoft.Json的JSON格式支持