【问题标题】:Why can't parse Json and Raw Result is show?为什么无法解析 Json 并显示原始结果?
【发布时间】:2019-11-14 16:34:21
【问题描述】:

我想以正确的格式返回结果的主体,而不是原始结果。

  public class tbl_Product
  {   
   public tbl_Product()
    {
        tbl_ProductPricing = new HashSet<tbl_ProductPricing>();
    }

    public Guid Id { get; set; }      
    public string ProductCode { get; set; }
    public string ProductName { get; set; }        

    [InverseProperty("Product")]
    public virtual ICollection<tbl_ProductPricing> tbl_ProductPricing { get; set; }
 }

以下是我返回时的 WebAPI 函数:

[HttpGet]
public async Task<ActionResult<ICollection<tbl_Product>>> GetProductList()
{
    return Ok(await _context.tbl_Product.Include(a => a.tbl_ProductPricing).ToListAsync());
}

但是,它返回的 格式 是这样的:

https://i.stack.imgur.com/BkDPy.jpg


我预期的格式是:

[
  {
    "id": "dc9874d0-9808-11e9-990d-014e614ad9ed",
    "ProductName": "Orange",
    "ProductCode": "A001",
    "ProductPricing":
    [
     {"id":"980874d0-014e-11e9-ad9e-114e614ad9ed",
      "Price":"5"
     }
    ]
  },
  {
    "id": "90d874d0-9808-11e9-990d-014e614ad9ed",
    "ProductName": "Apple",
    "ProductCode": "A002",
    "ProductPricing":
    [
     {"id":"ed0874d0-014e-11e9-ad9e-114e614ad9ed",
      "Price":"10"
     }
    ]
  }
 ]

我可以知道我的代码的哪一部分不正确吗?

【问题讨论】:

  • 文字比图片更容易阅读。
  • 你对比了实际的json结果和预期的结果吗?你发现它们之间有什么不同吗?
  • 是的,结果是一样的,但是格式不一样。以某种方式返回原始结果而不是 Json。 i.stack.imgur.com/BkDPy.jpg
  • WebAPI 不太可能生成无效的 JSON。您能否澄清一下您用来发送请求的内容以及原始响应的实际外观(as text inline in the question - edit post 这样做而不是评论图片链接)跨度>

标签: c# json entity-framework linq


【解决方案1】:

这对我有帮助,你可以在你的状态上全局设置它

  public void ConfigureServices(IServiceCollection services)
    {
       services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore); 
    }

【讨论】:

  • 谢谢!你拯救了我的一天!这正是我所期望的!
【解决方案2】:

您应该使用 Newtonsoft.Json.JsonConvert.SerializeObject() 手动格式化返回字符串;

那么格式就可以预测了

(旁白:我建议您粘贴结果字符串,以便我们可以详细比较两者,而不仅仅是一张没有显示整个响应的图片;运行差异将是我测试是否有发生了一些奇怪的事情,但我不能在图像上这样做)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    相关资源
    最近更新 更多