Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

994
Views
JsonSerializer.Deserialize está devolviendo un objeto vacío

Tengo un webapi que devuelve algo de Json:

 {"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} ]}

Luego trato de deserializar usando:

 using var response = await _httpClient.GetAsync($"{GetApiRouteFromEntity(entity)}/{entity.GetId()}"); response.EnsureSuccessStatusCode(); var responseContent = await response.Content.ReadAsStringAsync(); T? item = JsonSerializer.Deserialize<T>(responseContent);

pero esto me da una fábrica vacía con id 0 y todos los demás atributos en nulo

Fábrica.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}"; } }

Producto.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); } }

Supongo que es porque el accesorio de fábrica en los productos es nulo, pero no sé cómo solucionarlo.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

De los documentos :

De forma predeterminada, los nombres de propiedad y las claves del diccionario no se modifican en la salida JSON, incluido el caso.

Puede especificar la política de nomenclatura de propiedades:

 T? item = JsonSerializer.Deserialize<T>(responseContent, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });

para usar mayúsculas y minúsculas para todos los nombres de propiedades JSON, o marque todas las propiedades necesarias con JsonPropertyNameAttibute que contenga el nombre correcto:

 public class Factory : EntityBase { [DisplayName("ID")] [JsonPropertyName("id")] // and so on public int Id { get; set; } .... }
over 4 years ago · Santiago Trujillo Report

0

Las claves JSON son todas mayúsculas y minúsculas, pero los accesorios en sus clases están escritos en mayúsculas y minúsculas. Por ejemplo businessName vs. BusinessName . Por lo tanto, JsonSerializer no puede coincidir con ellos.

Puede inicializar el serializador de esta manera para ignorar las diferencias en la carcasa:

 var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; T? item = JsonSerializer.Deserialize<T>(responseContent, options);

Consulte los documentos para obtener más información: https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-character-casing

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!