我不确定我是否 100% 正确地描述了主题中的问题,但我相信示例可以解决问题。
我有如下所示的 JSON 结构(注意:这可能会改变的可能性很小,所以我需要倾向于通用解决方案)
一张发票有多个行项目:
{
"contactName": "Company",
"lineItems": [
{
"quantity": 7.0,
"description": "Beer No* 45.5 DIN KEG"
},
{
"quantity": 2.0,
"description": "Beer Old 49.5 DIN KEG"
}
],
"invoiceNumber": "C6188372"
}
这是想要的结果数据结构(具有重复数据和不同行项目信息的多张发票):
[{
"contactName": "Company",
"quantity": 7.0,
"description": "Beer No* 45.5 DIN KEG"
"invoiceNumber": "C6188372"
},{
"contactName": "Company",
"quantity": 2.0,
"description": "Beer Old 49.5 DIN KEG"
"invoiceNumber": "C6188372"
}]
因此,“发票”中的每个“行项目”都应该“导致”具有重复的其他元素的新发票。
接受结果数据结构的小变化,我可以围绕它调整我的代码。 我一直在使用几个类似的问题,例如:
- C# flattening json structure
- Flatten an array of objects that may contain arrays
- How can I flatten a collection of objects (which in turn contain collections)?
- Generically Flatten Json using c# (ETC)。我相信这是最接近的解决方案?但不确定是否有更好的方法
有关更多背景信息,我需要这个用于 CSV 导出。所以结果集应该是生成的 CSV 中的两行。
非常感谢任何提示/技巧。谢谢。
最佳答案
你可以用这样的函数来完成:
//Pass in the name of the array property you want to flatten
public string FlattenJson(string input, string arrayProperty)
{
//Convert it to a JObject
var unflattened = JsonConvert.DeserializeObject<JObject>(input);
//Return a new array of items made up of the inner properties
//of the array and the outer properties
var flattened = ((JArray)unflattened[arrayProperty])
.Select(item => new JObject(
unflattened.Properties().Where(p => p.Name != arrayProperty),
((JObject)item).Properties()));
//Convert it back to Json
return JsonConvert.SerializeObject(flattened);
}
然后这样调用它:
var flattenedJson = FlattenJson(inputJson, "lineItems");
关于c# - 将带有数组的 json 结构展平为多个没有数组的平面对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52057610/