首页 > 解决方案 > C#反序列化具有多个对象的JSON数组

问题描述

我正在接受一个我无法控制的 JSON 格式:

{
  "Transaction Information": [
    {
      "Type": "This is the Type"
    },
    {
      "Action": "No"
    },
    {
      "Owner": "Simpsons"
    },
    {
      "Buyer/Broker": "Y"
    },
    {
      "Compensation to Buyer": 3.0
    }
  ]
}

我想将它反序列化为一个类,例如:

public class Transaction
{
    [JsonProperty("Transaction Information")]
    public TransactionInformation[] TransactionInformation { get; set; }
}

public partial class TransactionInformation
{
    [JsonProperty("Type", NullValueHandling = NullValueHandling.Ignore)]
    public string Type { get; set; }

    [JsonProperty("Action", NullValueHandling = NullValueHandling.Ignore)]
    public string Action { get; set; }

    [JsonProperty("Owner", NullValueHandling = NullValueHandling.Ignore)]
    public string Owner { get; set; }

    [JsonProperty("Buyer/Broker", NullValueHandling = NullValueHandling.Ignore)]
    public string BuyerBroker { get; set; }

    [JsonProperty("Compensation to Buyer", NullValueHandling = NullValueHandling.Ignore)]
    public long? CompensationToBuyer { get; set; }
}

使用代码

var obj = JsonConvert.DeserializeObject<Transaction>(json);

但是,这给了我一个 Transaction.TransactionInformation 对象,其中包含 5 个记录,每个记录包含所有 5 个元素,每个记录具有除 5 个元素之一之外的所有空值。

在此处输入图像描述

有没有一种简单的方法可以在一条记录中返回所有 5 个元素?

标签: c#jsonserialization

解决方案


有没有一种简单的方法可以在一条记录中返回所有 5 个元素?

当然——只需将每个属性放在一个记录中:

var finalRecord = new TransactionInformation
{
    Type = obj.TransactionInformation.FirstOrDefault(x => !string.IsNullOrEmpty(x.Type))?.Type,
    Action = obj.TransactionInformation.FirstOrDefault(x => !string.IsNullOrEmpty(x.Action))?.Action,
    Owner = obj.TransactionInformation.FirstOrDefault(x => !string.IsNullOrEmpty(x.Owner))?.Owner,
    BuyerBroker = obj.TransactionInformation.FirstOrDefault(x => !string.IsNullOrEmpty(x.BuyerBroker))?.BuyerBroker,
    CompensationToBuyer = obj.TransactionInformation.FirstOrDefault(x => x.CompensationToBuyer.HasValue)?.CompensationToBuyer
};

您正在使用的 JSON 数据不是最方便的格式。在一个完美的世界中,它看起来像这样:

{
    "Transaction Information": [{
            "Type": "This is the Type",
            "Action": "No",
            "Owner": "Simpsons",
            "Buyer/Broker": "Y",
            "Compensation to Buyer": 3.0
        }
    ]
}

那么你正在做的事情会很好,你不必做这最后一步来规范化数据。


推荐阅读