简体   繁体   English

在不使用第三方库的情况下将 JsonArray 转换为正确格式的 csv 文件

[英]Convert JsonArray to to csv file in right format without using third party library

My dependency which is not third party我的依赖不是第三方

<dependency>
    <groupId>javax.json</groupId>
    <artifactId>javax.json-api</artifactId>
    <version>1.1.4</version>
</dependency>

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1.4</version>
</dependency>

JSon array test JSON数组测试

[{"name":"aondx","value":10,"date":"1999-01-09T14:30:53Z"}]

I am able to parse/ write into the a create a csv file but the issue is it is not in the right format in my csv file.我能够解析/写入创建 csv 文件,但问题是它在我的 csv 文件中的格式不正确。

public static void writeFilteredJsonToNewFile(JsonArray jsonArray) {
try {

    for (Object object : jsonArray) {
        JsonObject obj = (JsonObject) object;
        StringWriter writer = new StringWriter();
        JsonWriter jsonWriter = Json.createWriter(writer);
        jsonWriter.writeObject(obj);
        writer.close();

        FileWriter fileWriter = new FileWriter(diretory + name + ".csv");
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(writer.toString());
        bufferedWriter.close();
        System.out.println("Created new File!");
    }
} catch (IOException e) {
     e.printStackTrace();
}

} }

Result结果

在此处输入图像描述

Expected result (table format) in a csv file csv 文件中的预期结果(表格格式)

name姓名 value价值 date日期
aondx aondx 40 40 1999-01-09T14:30:53Z 1999-01-09T14:30:53Z
    If my understanding is correct, you want to convert the json into csv file but while writing to csv you are getting key value in each row instead of key in the first row and then value in the subsequent rows.
    
    I think if you follow below steps then you will able to achieve this:
    
    1) First convert your Json into the List<Map<String,String>> using below code
    
       
    
    >  ObjectMapper mapper = new ObjectMapper();
    >     List<Map<String, Object>> datas = mapper.readValue(jsonArray.toString(), new
    > TypeReference<List<Map<String, Object>>>(){});
    
    2) Find the keys from the json, which will be used as your column, assuming all the data having same keys.
    
       
    
    >  Set<String> columns = datas.get(0).keySet(); write columns as the
    > first row in the csv file.
    
    3) Iterate over the datas list and start writing the value row wise.
    

As you mentioned in the comment you doesn't not want to use the external library then instead of ObjectMapper you can use your JsonArray.正如您在评论中提到的,您不想使用外部库而不是 ObjectMapper,您可以使用您的 JsonArray。

  1. Instead of converting your json Array to List<Map<String,String>> and getting the keys you can do the same thing with JsonObject only as it implement Map only.而不是将您的 json Array 转换为 List<Map<String,String>> 并获取密钥,您可以仅对 JsonObject 执行相同的操作,因为它仅实现 Map。

     Set<String> columns = jsonArray.get(0).keySet(); this code should be before you are starting the loop.
  2. Inside the loop you are iterating over the jsonArray, there read the value .在循环内,您正在遍历 jsonArray,读取 value 。

 Set<String> columns = jsonArray.get(0).keySet(); for (Object object : jsonArray) { JsonObject obj = (JsonObject) object; List<String> dataRows = new ArrayList(); for(String column : columns ) { String value = (String)obj.get(column); dataRows.add(value); } ....... // write the value to file ....... }

If you are Interested in full solution, you can try this.如果您对完整解决方案感兴趣,可以试试这个。

 public static void writeFilteredJsonToNewFile(JsonArray jsonArray) { List<List<String>> allDatas = new ArrayList<>(); Set<String> columns = jsonArray.get(0).keySet(); allDatas.add(new ArrayList<>(columns)); for (Object object : jsonArray) { JsonObject obj = (JsonObject) object; List<String> dataRows = new ArrayList(); for(String column : columns ) { String value = (String)obj.get(column); dataRows.add(value); } allDatas.add(dataRows); } writeToCsvFile(allDatas,",","test-file.csv"); } public void writeToCsvFile(List<List<String>> thingsToWrite, String separator, String fileName){ try (FileWriter writer = new FileWriter(fileName)){ for (List<String> strings : thingsToWrite) { for (int i = 0; i < strings.size(); i++) { writer.append(strings[i]); if(i < (strings.length-1)) writer.append(separator); } writer.append(System.lineSeparator()); } writer.flush(); } catch (IOException e) { e.printStackTrace(); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不使用第三方库的情况下使用Java中另一个CSV文件中的值创建CSV文件 - How to create a CSV file using the values from another CSV file in Java without using third party library 在没有第三方库的情况下读取CSV文件 - Reading CSV file without third-party libraries Kotlin-Android序列化json不使用第三方库 - Kotlin-Android serialize json without using third party library 不使用第三方库将xml字符串转换为JSON字符串 - Convert xml string to JSON string without using third party libs 使用第三方Android库加载PPT文件 - Load PPT File using Third Party Android Library 有没有不用第三方库就可以创建tar文件的方法? - Is there any way to create tar file without using third party libraries? 有没有一种简单的方法可以将 java 字符串转换为包括变音符号在内的标题大小写,无需第三方库 - Is there a simple way to convert java string to title case including diacritics, without third party library 使用带有libgdx和GWT的第三方库 - Using a third-party library with libgdx and GWT 不使用任何第三方库的有关Twitter登录的指南 - Guide about twitter login in web without using any third party library 使用第三方Java库重新实现AES加密,不受美国法律限制 - Reimplement AES encryption using third-party Java library without US law limitations
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM