c# - 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 个元素?
解决方案
有没有一种简单的方法可以在一条记录中返回所有 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
}
]
}
那么你正在做的事情会很好,你不必做这最后一步来规范化数据。
推荐阅读
- sapui5 - 您可以在对话框中放置多个输入和文本区域吗?
- c# - 如何确定列表是否包含任何对象
- html - 单击后如何使我的汉堡菜单按钮更改颜色?
- android - 使用 android studio 构建 snapdragon 相机应用
- java - 通过身份验证保护应用程序并从类级别的请求标头解析用户名
- c++ - 将初始化列表传递给基于向量的构造函数
- html - 如何在我网站的博客中嵌入网站?
- docker - 使用 sbt-docker 插件将文件从根级项目目录复制到 docker 映像中
- c# - 是否有另一个像 Regex 这样的网络标准 API 来检查 URI 是否与模板匹配?
- lua - 这是在 Lua 中为我的 FSM 图实现基本 FSM 的正确方法吗?