【问题标题】:error: SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at错误:SyntaxError:JSON.parse (<anonymous>) 处的 JSON 输入意外结束
【发布时间】:2020-03-09 06:44:55
【问题描述】:

我正在加载嵌套对象,但传入的数据没有正确关闭 json“[”: 有人可以帮忙吗,我无法检索数据。

[{"Id":1,"Barcode":"N001",.....,"ProductSubCategoryID":1,"SellerId":0,"SellerName":null,"ProductSubCategory":{"ProductSubCategoryID ":1,"SubCategoryName":"乳液","产品":["

public class Product
{
    [Key]
    public int Id { get; set; }
    .
    .
    [ForeignKey("ProductSubCategoryID")]
    public virtual ProductSubCategory ProductSubCategory { get; set; }
}

public class ProductSubCategory
{
    [Key]
    public int ProductSubCategoryID { get; set; }
    [Required]
    [Column(TypeName = "nvarchar(100)")]
    public string SubCategoryName { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}
    // GET: api/Product
    public async Task<Object> GetProducts()
    {
        return Ok(await _context.Products.Include(p => p.ProductSubCategory).ToListAsync());
    }

readonly BaseURI = 'http://localhost:54277/api/Product';

  private   product$: Observable<Product[]>;

  // Get All Products
  getProducts(): Observable<Product[]> {
    if (!this.product$) {
      this.product$ = this.http.get < Product[] > (this.BaseURI + '/GetProducts').pipe(shareReplay());
    }
    return this.product$;
  }

【问题讨论】:

  • 您应该尝试打印数据。错误消息是说您的数据没有正确的 JSON 格式并且无法解析。您可以在这里验证您的输入:jsonlint.com

标签: c# asp.net angular asp.net-core-webapi typescript-typings


【解决方案1】:

问题在于序列化。由于循环引用,ASP.Net Core 无法正确序列化为 JSON。 Product 具有 ProductSubCategory 类型的属性,ProductSubCategory 具有 Product 类型的属性,这会导致循环引用。

所以 ProductABC 具有 ProductSubCategoryABC,它又具有产品集合并具有 ProductABC。

为避免循环引用,请修改您的 startup.cs 并指定 options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore

services.AddMvc()
    .AddJsonOptions(options => {
        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    });

【讨论】:

    猜你喜欢
    • 2020-10-05
    • 2021-02-27
    • 2018-12-09
    • 2021-06-08
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    相关资源
    最近更新 更多