我有一些这种格式的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
类型。当循环遍历这些项时,我如何获得每个项的类型,即TransactionSaleItem
和TransactionReturnItem
?
简化的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>
{
}
1条答案
按热度按时间p4rjhz4m1#
每个对象都使用
"$type"
字段指定其类型。您应该能够分别将这些键Map到TransactionSaleItem
和TransactionReturnItem
。如果你使用的是System.Text.Json,这是用JsonDerivedType attribute完成的: