【发布时间】:2022-02-17 22:39:28
【问题描述】:
我有一个返回一些 Json 的 webapi:
{"id":9,"businessName":"dummy","address":"pluto","products":[
{"id":762,"description":"Centralized needs-based website","price":1281.24,"stock":1600,"categories":[],"factory":null},
{"id":1027,"description":"Realigned 6th generation knowledge base","price":2398.16,"stock":19583,"categories":[],"factory":null},
{"id":1392,"description":"User-centric zero administration array","price":998.07,"stock":6124,"categories":[],"factory":null},
{"id":1800,"description":"Team-oriented reciprocal core","price":4422.95,"stock":17372,"categories":[],"factory":null},
{"id":2763,"description":"Sharable needs-based hierarchy","price":4122.98,"stock":17397,"categories":[],"factory":null},
{"id":6189,"description":"Re-engineered hybrid emulation","price":395.09,"stock":532,"categories":[],"factory":null}
]}
然后我尝试反序列化使用:
using var response = await _httpClient.GetAsync($"{GetApiRouteFromEntity(entity)}/{entity.GetId()}");
response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsStringAsync();
T? item = JsonSerializer.Deserialize<T>(responseContent);
但这给了我一个 id 为 0 且所有其他属性为 null 的空工厂
Factory.cs
public class Factory : EntityBase
{
[DisplayName("ID")]
public int Id { get; set; }
[DisplayName("Nome Business")]
public string? BusinessName { get; set; }
[DisplayName("Indirizzo")]
public string? Address { get; set; }
[DisplayName("Prodotti")]
public virtual ICollection<Product> Products { get; set; }
public override string ToString()
{
return $"[{Id}] {BusinessName}";
}
}
Product.cs
public class Product : EntityBase
{
[DisplayName("ID")]
public int Id { get; set; }
[DisplayName("Descrizione")]
public string? Description { get; set; }
[DisplayName("Prezzo")]
public float Price { get; set; }
[DisplayName("Magazzino")]
public int Stock { get; set; }
[DisplayName("Categorie")]
public virtual ICollection<Category> Categories { get; set; }
[DisplayName("Fabbrica")]
public virtual Factory Factory { get; set; }
public override string ToString()
{
return $"[{Id}] {Description}";
}
}
EntityBase.cs
public abstract class EntityBase
{
public virtual object GetId()
{
return GetType().GetProperty("Id").GetValue(this);
}
}
我猜是因为产品中的工厂属性为空,但不知道如何解决这个问题
【问题讨论】:
-
responseContent 在请求结束时 Json 已满,但序列化程序只是返回一个空实体
-
所以
TinJsonSerializer.Deserialize<T>(responseContent)是Factory? -
是的,事实上当调试项目是一个工厂但它有每个道具作为默认值
-
您的 JSON 无效。 “产品”及其数组之间没有 :
-
我只是错误地粘贴了 json,请提醒我!
标签: c# json asp.net-web-api system.text.json jsonserializer