Issue
I'm loading nested object but the data coming in does'nt have the correct closing for json "[": Can someone help, I can't be able to retrieve the data.
[{"Id":1,"Barcode":"N001",.....,"ProductSubCategoryID":1,"SellerId":0,"SellerName":null,"ProductSubCategory":{"ProductSubCategoryID":1,"SubCategoryName":"Lotion","Products":["
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());
}
<---- Angular Code ---->
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$;
}
Solution
The problem is in serialization. due to circular reference, ASP.Net Core is not able to serialize to JSON correctly. Product has the property of type ProductSubCategory and again ProductSubCategory has the property of type Product which causes a circular reference.
So ProductABC has ProductSubCategoryABC which again has a collection of product and has ProductABC.
To avoid circular reference modify your startup.cs
and specify options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
Answered By - Arjun Vachhani
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.