C# -如何在ICollection JSON属性中定义类型?

y4ekin9u  于 2023-10-21  发布在  C#
关注(0)|答案(1)|浏览(171)

我有一些这种格式的JSON,其中包括一个集合。

{
  "Store": 12,
  "TransactionItems": {
    "$type": "System.Collections.ObjectModel.Collection`1[[BaseTransactionItem, Common]], mscorlib",
    "$values": [
      {
        "$type": "TransactionSaleItem, Common",
        "Description": "Grey Shirt",
        "ActualSalePrice": 40.0,
        "ActualSalePricePerItem": 40.0
      },
      {
        "$type": "TransactionReturnItem, Common",
        "Description": "Red Shirt",
        "ActualSalePrice": -30.0,
        "ActualSalePricePerItem": -30.0
      }
    ]
  },
  "CountryCode": "GB"
}

当使用Newtonsoft的nuget包实现这一点时,我可以访问TransactionItems,它有两个项目的集合,它们都是BaseTransactionItem类型。当循环遍历这些项时,我如何获得每个项的类型,即TransactionSaleItemTransactionReturnItem
简化的C#代码:

[DataContract(IsReference = true)]
public class Transaction : IEquatable<Transaction>
{
    [DataMember]
    public int Store { get; set; }

    [DataMember]
    public ICollection<BaseTransactionItem> TransactionItems { get; set; }

    [DataMember]
    public string CountryCode { get; set; }
}

[DataContract]
[KnownType(typeof(TransactionOrderItem))]
[KnownType(typeof(TransactionReturnItem))]
[KnownType(typeof(TransactionSaleItem))]
public class BaseTransactionItem : IEquatable<BaseTransactionItem>
{
}

[DataContract]
public class TransactionReturnItem : BaseTransactionItem, IEquatable<TransactionReturnItem>
{
}

[DataContract]
public class TransactionSaleItem : BaseTransactionItem, IEquatable<TransactionSaleItem>
{
}
p4rjhz4m

p4rjhz4m1#

每个对象都使用"$type"字段指定其类型。您应该能够分别将这些键Map到TransactionSaleItemTransactionReturnItem
如果你使用的是System.Text.Json,这是用JsonDerivedType attribute完成的:

[JsonDerivedType(typeof(TransactionSaleItem), typeDiscriminator: "TransactionSaleItem, Common")]
[JsonDerivedType(typeof(TransactionReturnItem), typeDiscriminator: "TransactionReturnItem, Common")]
public class BaseTransactionItem
{
   ...
}

相关问题