c# - 将带有数组的 json 结构展平为多个没有数组的平面对象

标签 c# json recursion json.net

我不确定我是否 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"
}]

因此,“发票”中的每个“行项目”都应该“导致”具有重复的其他元素的新发票。

接受结果数据结构的小变化,我可以围绕它调整我的代码。 我一直在使用几个类似的问题,例如:

有关更多背景信息,我需要这个用于 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/

相关文章:

c - 使用c中多维数组中的行的递归函数中的语法错误

c# - Entity Framework 5 升级后多对多关系左右键翻转

c# - 使用窗口窗体中的按钮从列表框中删除所选项目

json - 如何向 Laravel 分页 json 响应添加自定义属性

javascript - AngularJS - 无论返回的 http 状态如何,如何捕获从 GET 服务方法返回的 JSON

javascript - JSON 数据网格就像 jQuery 中的 Excel

c# - 打开 excel 工作簿但将计算设置为手动

c# - moq No setups configured error,如何快速正确添加setup

algorithm - 求解递归函数的递归关系

go - 使用定义的类型而不是类型文字的递归类型约束?