Home > Software design >  Convert JsonArray to to csv file in right format without using third party library
Convert JsonArray to to csv file in right format without using third party library

Time:06-28

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

[{"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.

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 enter image description here

Expected result (table format) in a csv file

name value date
aondx 40 1999-01-09T14:30:53Z

CodePudding user response:

    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.

  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.

     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 .

 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();
    }
}
  • Related