在 Java 中将嵌套的 Json 文件转换为 CSV

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18007858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:44:39  来源:igfitidea点击:

Converting Nested Json files to CSV in java

javajsoncsvgson

提问by arun

    {
    "Employee": [
        {
            "empMID": "mock:1",
            "comments": [],
            "col1": "something",
            "contact": [{"address":"2400 waterview", "freetext":true}
                         ],
            "gender": "male"
        },
        {
            "empMID": "mock:2",
            "comments": [],
            "col1": "something",
            "contact": [{"address":"2200 waterview", "freetext":true}
                         ],
            "gender": "female"
        }
    ],
    "cola": false,
    "colb": false
}

This is how my Json file looks .I m required to convert this json to a csv .(I m trying to convert a multi-dimesional data to 2d).I m using gson for my purpose.I cannot use gson.fromgson() function to object map with a template because it should be generic .

这就是我的 Json 文件的外观。我需要将此 json 转换为 csv 。(我正在尝试将多维数据转换为 2d)。我使用 gson 来实现我的目的。我不能使用 gson.fromgson()使用模板映射对象的函数,因为它应该是通用的。

I know we can use CDL to convert jsonarray to csv format but It wont work in my case .

我知道我们可以使用 CDL 将 jsonarray 转换为 csv 格式,但在我的情况下它不起作用。

my csv format looks like

我的 csv 格式看起来像

Employee*
empMID,comment.$,contact.address,contact.freetext,gender
mock:1,,2400 waterview,TRUE,male
mock:123,,2200 waterview,TRUE,female
colA#
TRUE
colB#
FALSE

I tried using google-GSON api to convert to this format .But I m not able to convert to this format .I have used * to represent its a json array and # to represent its a primitive type and contact.address to represent nested array inside another json array .I having problem relating this nested structure .I m able to traverse everything recursively like a column. Thanks in advance

我尝试使用 google-GSON api 转换为这种格式。但我无法转换为这种格式。我使用 * 表示其 json 数组和 # 表示其原始类型和 contact.address 表示嵌套数组在另一个 json 数组中。我在关联这个嵌套结构时遇到问题。我能够像列一样递归地遍历所有内容。提前致谢

public static void main(String[] args) throws IOException{

        BufferedReader reader=null;
        StringBuilder content=null;
        String result=null;

            reader = new BufferedReader(new FileReader("temp.json"));

            String line = null;
            content= new StringBuilder();

            while ((line = reader.readLine()) != null) {
            content.append(line);
            }
            reader.close();
            result= content.toString();

            JsonElement jelement = new JsonParser().parse(result);

            printJsonRecursive(jelement);


        }


    public static void printJsonRecursive(JsonElement jelement){


        if(jelement.isJsonPrimitive()){

            System.out.println(jelement.getAsString());
            return;
        }
        if(jelement.isJsonArray()){

            JsonArray jarray= jelement.getAsJsonArray();
            for(int i=0;i<jarray.size();i++){
                JsonElement element= jarray.get(i);
                printJsonRecursive(element);
            }
            return;

        }
        JsonObject  jobject= jelement.getAsJsonObject();

        Set<Entry<String, JsonElement>> set= jobject.entrySet();

        for (Entry<String, JsonElement> s : set) {

            printJsonRecursive(s.getValue());


        }

    }



}

回答by rocketboy

You are not printing the key. This should fix it.

您没有打印key. 这应该解决它。

    for (Entry<String, JsonElement> s : set) {

        System.out.println(s.getKey());            //Added
        printJsonRecursive(s.getValue());

    }

You can take care of \ns from here.

你可以\n从这里照顾s。

EDIT

编辑

If you want to print the keys just once for repeating json objects, create a Java beanto hold the data and populate itduring your recursion. Once the bean is complete, add a method there to print all the data in the format you want (printing keys only once and so on).

如果您只想打印一次重复 json 对象的键Java bean,请populate it在递归期间创建一个来保存数据。一旦 bean 完成,在那里添加一个方法,以您想要的格式打印所有数据(仅打印一次密钥等等)。

回答by LeOn - Han Li

You can achieve this thru reflection if you have a object mapped to the json.

如果您有一个映射到 json 的对象,您可以通过反射来实现这一点。

  1. use gson/Hymanson to convert json to java object

  2. append fields using reflection by iterating the class and get any field you interested in.

  3. append value with reflection by getting value from the target object.

  1. 使用 gson/Hymanson 将 json 转换为 java 对象

  2. 通过迭代类使用反射附加字段并获取您感兴趣的任何字段。

  3. 通过从目标对象获取值来附加反射值。

More detail look at my blog post below:

更详细的看我下面的博文:

vcfvct.wordpress.com/2015/06/30/converting-nested-json-files-to-csv-in-java-with-reflection/

vcfvct.wordpress.com/2015/06/30/converting-nested-json-files-to-csv-in-java-with-reflection/

回答by skap

You can use the library json2flatfor converting your JSONto CSV.

您可以使用库json2flat将您的JSON转换为CSV

This library doesn't require any POJO's. It simply takes your JSON as stringand returns a 2D representationof it in the format of List<Object[]>.

这个库不需要任何POJO 的. 它只是将您的JSON 作为字符串并以.json格式返回它的2D 表示形式List<Object[]>

For example for the JSON:

例如对于 JSON:

{
    "Employee": [
        {
            "empMID": "mock:1",
            "comments": [],
            "col1": "something",
            "contact": [{"address":"2400 waterview", "freetext":true}
                         ],
            "gender": "male"
        },
        {
            "empMID": "mock:2",
            "comments": [],
            "col1": "something",
            "contact": [{"address":"2200 waterview", "freetext":true}
                         ],
            "gender": "female"
        }
    ],
    "cola": false,
    "colb": false
}

It gives an output:

它给出了一个输出:

/cola,/colb,/Employee/empMID,/Employee/col1,/Employee/gender,/Employee/contact/address,/Employee/contact/freetext
,,"mock:1","something",,"2400 waterview",true
,,"mock:2","something",,"2200 waterview",true
false,false,,,,,