{
    "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
}


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

我知道我们可以使用CDL将jsonarray转换为csv格式,但对我而言不起作用。

我的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


我尝试使用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());


        }

    }



}

最佳答案

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


使用gson / jackson将json转换为java对象
通过对类进行迭代来使用反射追加字段,并获取您感兴趣的任何字段。
通过从目标对象获取值来附加反射值。


更多细节请看下面我的博客文章:

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

07-24 09:49
查看更多