我有一个csv文件,并希望通过在java中使用多列csv进行分组来形成JSON对象

时间:2016-07-06 12:24:41

标签: java json csv

> CSV外观:使用(,)已分配值

    Col_1   Col_2   Col_5   Col_6

    1   YYY1    1111    CDX00001
    1   YYY2    1111    CDX00001

    2   YYY3    3333    CDX00002

    2   YYY4    2222    CDX00001

    2   YYY5    3333    CDX00002
    2   YYY6    3333    CDX00002
    2   YYY7    3333    CDX00002
    2   YYY8    4444    CDX00002
    2   YYY9    4444    CDX00002

> **我使用下面的代码将2列分组,JSON结果如下所示。

     "CDX00002$@4444": [
        {
          "Col_5": "4444",
          "Col_6": "CDX00002",
          "Col_1": "2",
          "Col_2": "YYY8"
        },
        {
          "Col_5": "4444",
          "Col_6": "CDX00002",
          "Col_1": "2",
          "Col_2": "YYY9"
        }
      ],
      "CDX00002$@3333": [
        {
          "Col_5": "3333",
          "Col_6": "CDX00002",
          "Col_1": "2",
          "Col_2": "YYY3"
        },
        {
          "Col_5": "3333",
          "Col_6": "CDX00002",
          "Col_1": "2",
          "Col_2": "YYY5"
        },
        {
          "Col_5": "3333",
          "Col_6": "CDX00002",
          "Col_1": "2",
          "Col_2": "YYY6"
        },
        {
          "Col_5": "3333",
          "Col_6": "CDX00002",
          "Col_1": "2",
          "Col_2": "YYY7"
        }
      ],
      "CDX00001$@1111": [
        {
          "Col_5": "1111",
          "Col_6": "CDX00001",
          "Col_1": "1",
          "Col_2": "YYY1"
        },
        {
          "Col_5": "1111",
          "Col_6": "CDX00001",
          "Col_1": "1",
          "Col_2": "YYY2"
        },
        {
          "Col_5": "1111",
          "Col_6": "CDX00001",
          "Col_1": "2",
          "Col_2": "YYY10"
        }
      ],
      "CDX00001$@2222": [
        {
          "Col_5": "2222",
          "Col_6": "CDX00001",
          "Col_1": "2",
          "Col_2": "YYY4"
        }
      ]
    }

>使用的代码:

                Map  namesByCompany = list.stream()
                          .collect(Collectors.groupingBy(item->item.get("Col_6") +"$@"+item.get("Col_5"),Collectors.toList()));

             Gson gson = new GsonBuilder().setPrettyPrinting().create(); 
             System.out.println("--result---"+gson.toJson(namesByCompany));

=============================================== ==========

  

详细信息:

But problem here my groupBy columns is dynamic and cannot be hard coded as above, If we get another one  columns then JSON should be prepared by considering new Groupby as well.  I need to prepare a JSON from CSV somehow using dynamic gorupby columns. I tried in java but if you any other tools or coding please post here . Thanks in advance

1 个答案:

答案 0 :(得分:0)

如果每一行都是一个组,你可以让它将组添加到该组的JSON,直到它找不到另一个组,''