【问题标题】:JsonSerializer.Deserialize is returning empty objectJsonSerializer.Deserialize 正在返回空对象
【发布时间】: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 已满,但序列化程序只是返回一个空实体
  • 所以T in JsonSerializer.Deserialize&lt;T&gt;(responseContent)Factory ?
  • 是的,事实上当调试项目是一个工厂但它有每个道具作为默认值
  • 您的 JSON 无效。 “产品”及其数组之间没有 :
  • 我只是错误地粘贴了 json,请提醒我!

标签: c# json asp.net-web-api system.text.json jsonserializer


【解决方案1】:

来自docs

默认情况下,JSON 输出中的属性名称和字典键不变,包括大小写。

您可以指定属性命名策略:

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

对所有 JSON 属性名称使用驼峰式大小写,或使用包含正确名称的 JsonPropertyNameAttibute 标记所有需要的属性:

public class Factory : EntityBase
{
    [DisplayName("ID")]
    [JsonPropertyName("id")] // and so on
    public int Id { get; set; }
    ....
}

【讨论】:

  • 天哪,我花了 5 个小时在这上面,太棒了!
  • @IvanAmbla 很乐意提供帮助!
  • 我现在有一个新问题:-:,如果我尝试序列化对象,它会给我一个带有 PascalCase 的漂亮字符串,但如果我尝试使用 JsonSerializer.Serialize(lastEntity.Entity,new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }) 它只是给了我{}
  • 使用相同的选项返回 {} 不使用任何选项返回 Pascal,如有必要,我会准备一个 repo,我会花一些时间,再次寻求帮助!
  • 我可以打开一个新的讨论,我认为它更好,因为即使相关的是一个不同的问题我今晚打开它
【解决方案2】:

JSON 键都是驼峰式大小写,但你的类中的道具是用帕斯卡大小写的。例如。 businessNameBusinessName。因此 JsonSerializer 无法匹配它们。

您可以像这样初始化序列化程序以忽略大小写的差异:

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

有关详细信息,请参阅文档:https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-character-casing

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 2021-09-03
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多