Okay so this is my code –>
first we have a normal class:
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;
}
@Override
public String toString() {
return
id+" "+name+" "+nation+"n";
}
}
then this is my main class trying to convert every class object to a json file using GSON
class Main{
public static void main(String[] args){
Fencers fencer1 = new Fencers("m","egy",100);
Fencers fencer2 = new Fencers("342","egy",120);
String json = new Gson().toJson(fencer1);
json += new Gson().toJson(fencer2);
System.out.println(json);
}
}
the only problem here is it prints json
like this:
{
"name":"m",
"nation":"egy",
"id":100
}
{"name":"342",
"nation":"egy",
"id":120
}
and I want them to be like this
[
{
"name":"m",
"nation":"egy",
"id":100
},
{
"name":"342",
"nation":"egy",
"id":120
}
]
really appreciate the help
2
Answers
You need to collect the elements in a collection (or just array).
Try this: