【问题标题】:.net Core 3.1 return empty JObject.net Core 3.1 返回空的 JObject
【发布时间】:2021-10-15 19:05:10
【问题描述】:

我遇到了一个奇怪的问题。我创建了 Web API 功能,当我返回带有 JObject 成员的 DTO 类的答案时,我在 Postman 中得到空数组。 代码:

DTO:

public class EntityAttributesDTO
{
    public JObject Json { get; set; }
}

农场控制器:

[AllowAnonymous]
[HttpGet("entities")]
public async Task<JsonResult> GetEntitiesAsync()
{
    return await Mediator.Send(new AttributesHandler.Query { });
}

AttributesHandler:

   public async Task<List<EntityAttributesDTO>> Handle(Query request, CancellationToken cancellationToken)
    {
        List<EntityAttributesDTO> returnAttributes = new List<EntityAttributesDTO>();
        string str = @"{ ""context_name"": { ""lower_bound"": ""value"", ""upper_bound"": ""value"" } }";

         returnAttributes.Add(
              new EntityAttributesDTO
              {
                   Json = JObject.Parse((string)str);
              }
         );

        return returnAttributes;
    }

但在 Postman 中,我得到的是空的 JSON,只有括号。核心 3.1 中可能发生了一些变化,我不明白。我该如何解决我的问题?我需要将字符串转换为 JSON 格式。但是表只有id、parentid、type、value。也就是递归。属性的数量是动态的。

【问题讨论】:

  • 我不明白你为什么返回原始 JSON,而不是一个被序列化为 JSON 的适当实体。
  • 只是虚拟的,用于测试

标签: c# asp.net .net asp.net-core .net-core


【解决方案1】:

这对我有用,您可以将其与它进行比较。请允许我发布作为答案,以便我可以清楚地显示出来。当然,如果我在某些地方误解了,请添加更多详细信息,以便我们可以通过他们找到问题。

我新创建了一个 asp.net core 3.1 MVC 项目,这是我的控制器:

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using WebApplication2.Models;

namespace WebApplication2.Controllers
{
    public class HelloController : Controller
    {
        public JsonResult Index()
        {
            string str3 = @"{ ""context_name"": { ""lower_bound"": ""value"", ""upper_bound"": ""value"" } }";
            List<EntityAttributesDTO> list = new List<EntityAttributesDTO>();
            list.Add(new EntityAttributesDTO { Json = JObject.Parse(str3) });
            return Json(list);
        }
    }
}

我在 Startup.cs 中的 ConfigureServices 方法

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews().AddNewtonsoftJson();
        }

别忘了添加 nuget 包:

这是测试结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2020-12-01
    相关资源
    最近更新 更多