Json.NET 反序列化 属性 而不反序列化其上方的父对象

Json.NET Deserialize Property Without Deserializing Parent Object Above It

我正在尝试接受这个 JSON:

{
      "title":"string",
      "description":"string",
      "date":"2021-04-19T01:05:38.000Z",
      "image":"url",
      "images":[
         "url1",
         "url2"
      ],
      "attributes":{
         "phonebrand":"x",
         "phonecarrier":"y",
         "forsaleby":"z",
         "price":12345,
         "location":"daLocation",
         "type":"OFFERED"
      },
      "url":"url to listing"
   }

并将其转换为此 C# 对象:

public class Listing {
        [JsonProperty("title")]
        public string Title { get; set; }
        [JsonProperty("description")]
        public string Description { get; set; }
        [JsonProperty("date")]
        public DateTime? Date { get; set; }
        [JsonProperty("image")]
        public string Image { get; set; }
        [JsonProperty("images")]
        public string[] Images { get; set; }
        [JsonProperty("url")]
        public string Url { get; set; }
        [JsonProperty("price")]
        public decimal Price { get; set; }
        [JsonProperty("locationId")]
        public int LocationId { get; set; }
        [JsonProperty("categoryId")]
        public int CategoryId { get; set; }
        [JsonProperty("sortByName")]
        public string SortByName { get; set; }
        [JsonProperty("q")]
        public string Q { get; set; }
        [JsonProperty("location")]
        public string Location { get; set; }
        [JsonProperty("type")]
        public string Type { get; set; }
        [JsonProperty("forsaleby")]
        public string ForSaleBy { get; set; }
        [JsonProperty("fulfillment")]
        public string Fulfillment { get; set; }
        [JsonProperty("payment")]
        public string Payment { get; set; }
        [JsonProperty("phonebrand")]
        public string? PhoneBrand { get; set; }
        [JsonProperty("phonecarrier")]
        public string? PhoneCarrier { get; set; }
}

我的问题是,我正在尝试反序列化 pricephonebrand 等属性,但这些属性位于 JSON 中的一个对象下。因此,当我尝试像这样反序列化它们时,无法找到这些属性并将其设置为 null。如何在不更改 C# Class 以包含 Attributes class 的情况下反序列化这些属性?我想这样做是因为我认为与我正在接受的 JSON 相比,这是一个 cleaner/better 设计。

我建议两种非常明确且易于理解的方法,供下一个查看代码的开发人员使用。

两个class是

创建用于反序列化的中间 dto class,然后从该中间对象创建业务逻辑对象。

var withAttributes = Deserialise<ListingDto>();

var flatObject = new Listing(withAttributes);

一个class

您可以在顶层提供进入子classes 的访问器。

public class Listing
{
  public AttributesDto Attributes {get; set}

  ... 

  public string Url => Attributes.Url; // Maybe '?.Url'
}