I want to convert Json file to CSV file. I passed data from json to java object then I try to write Java object to CSV file but it gives NPE. It probably not correctly gets the data from JSON. I'm not sure what it is.
Class for reading json to java object
public Student convertJson(File jsonFile) {
Gson gson = new Gson();
Student std;
try{
std = gson.fromJson(new FileReader(jsonFile),Student.class);
return std;
}
catch (FileNotFoundException e) {
return null;
}
}
Class for converting object to csv
private final String SEPARATOR = ", ";
public void toCSV(List<Student> student) {
try{
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("group.csv"),"UTF-8"));
for(Student std: student){
StringBuffer oneLine = new StringBuffer();
oneLine.append(std.getEmail());
oneLine.append(SEPARATOR);
oneLine.append(std.getName());
oneLine.append(SEPARATOR);
oneLine.append(std.getScoreGroup());
oneLine.append(SEPARATOR);
oneLine.append(std.getCommentGroup());
bw.write(oneLine.toString());
bw.newLine();
}
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
Main
File newfile = new File(pathName);
List<File> files= file.findFile(newfile); // step 1 find files and return arralist of files
System.out.println(files);
List<Student> students = new ArrayList<>(); // array list of objects Student
ReadJson fiel = new ReadJson(); // parses passed json file and returns Student file
List<Group> info = new ArrayList<>();
java.util.Collections.sort(info);
for(int i=0;i<files.size();i++){
Student temp = fiel.convertJson(new File(files.get(i).getName()));
students.add(temp);
}
ConvertJSONFiles json = new ConvertJSONFiles();
json.toCSV(students);
Error
Exception in thread "main" java.lang.NullPointerException
at ca.cmpt213.as2.ConvertJSONFiles.toCSV(ConvertJSONFiles.java:16)
at com.company.Main.main(Main.java:44)
Disconnected from the target VM, address: '127.0.0.1:63683', transport: 'socket'
New problem: Now it says it cannot read because there should be object not array.
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 2 column 13 path $.group at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129) at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220) at com.google.gson.Gson.fromJson(Gson.java:888) at com.google.gson.Gson.fromJson(Gson.java:826) at ca.cmpt213.as2.ReadJson.convertJson(ReadJson.java:17) at com.company.Main.main(Main.java:36)