so these are my classes
public class Fencers{
private String name,nation;
private int id;
public Fencers(String name, String nation,int id) {
this.name = name;
this.nation = nation;
this.id = id;
}
}
the following class stores the other class objects in an Array List
import java.util.ArrayList;
public class FencersList {
private ArrayList<Fencers> collection;
public FencersList(){
collection = new ArrayList<Fencers>();
}
public ArrayList<Fencers> getCollection() {
return collection;
}
public void addfencer(Fencers fencer){
collection.add(fencer);
}
public String toString(){ //the toString method
System.out.println("**************** FENCERS ****************");
String total = "\n";
for (int i = 0;i<collection.size();i++){
Fencers b = (Fencers) collection.get(i);
total = total + b.toString();
}
return total;
}
public void printFencers(){
System.out.println(this);
}
}
and finally here is the main
import com.google.gson.Gson;
import java.io.*;
class Main{
public static void main(String[] args){
Fencers fencer1 = new Fencers("m","egy",100);
Fencers fencer2 = new Fencers("342","egy",120);
FencersList list = new FencersList();
list.addfencer(fencer1);
list.addfencer(fencer2);
Gson gson = new Gson();
try (PrintWriter out = new PrintWriter(new FileWriter("file.json"))) {
String jsonString = gson.toJson(list.getCollection());
out.write(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader br = new BufferedReader(new FileReader("file.json"));
Fencers[] fencers = gson.fromJson(br,Fencers[].class);
System.out.println(fencers);
list.addfencer(fencers);
} catch (Exception f){
f.printStackTrace();
}
}
}
here I managed to save FencersList
class object in a the file.json
everything works fine
my only problem here is I can't convert the data back to FencersList
simply because this format makes it so that Fencers
is an array and FencerList
only accepts normal class objects from Fencers
and when I fix it and make it normal it gives me an error Expected BEGIN_OBJECT but was BEGIN_ARRAY
so I am a little bit stuck.
this is the file.json
btw
[
{
"name":"m",
"nation":"egy",
"id":100}
,{
"name":"342",
"nation":"egy",
"id":120
}
]
Your error here is that when you saving collection to json file, but trying to read collection as FencersList object.
I am talking about this line:
String jsonString = gson.toJson(list.getCollection());
This means that if you want to convert this jsonString back target object type should be the same as result of list.getCollection(), i.e. List. But instead of this you are trying deserialize json string to Fencers[]. It will not work
In order to be able to deserialize to FencersList you should create your json with
String jsonString = gson.toJson(list);
Which will make your json looks like this (collection is the name of field in your FencersList class):
{ "collection":[{"name":"m", "nation":"egy", "id":100}] }