skip to Main Content

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


  1. You need to collect the elements in a collection (or just array).

    Fencers fencer1 = new Fencers("m","egy",100);
    Fencers fencer2 = new Fencers("342","egy",120);
    List<Fencers> list = Arrays.asList(fencer1, fencer2);
    String json = new Gson().toJson(list);
    System.out.println(json);
    
    Login or Signup to reply.
  2. Try this:

    public static void main(String[] args){
            Fencers fencer1 = new Fencers("m","egy",100);
            Fencers fencer2 = new Fencers("342","egy",120);
            List<Fencers> fencerList = new ArrayList<>();
            fencerList.add(fencer1);
            fencerList.add(fencer2);
            String json = new Gson().toJson(fencerList);
            System.out.println(json);
         
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search