-4

I want to write an array of objects to a JSON file. For example:

public class Passanger{
  private String    name;
  private String surname;
 }

I want to create object array(Passenger[] Passengers) and save it as a JSON file with Gson. JSON example:

[
    {"name": "jack", "surname": "dere"},
    {"name": "adam", "surname": "ered"}
]
Lyubomyr Shaydariv
  • 20,327
  • 12
  • 64
  • 105
Eic Dafusen
  • 11
  • 2
  • 6

1 Answers1

0

To write JSON's data structure you can use for example

    public void toFillData() {
        JSONObject obj = new JSONObject();
        JSONArray list = new JSONArray();
        JSONArray listP = new JSONArray();

//Cycle for passengers

    list.add("of_name");
    list.add("of_surname");

// To build one passenger like json object 
    obj.put("passenger", list);

// To add passenger to list of passengers

       listP.add(obj);

    try {

// Save to file
        FileWriter file = new FileWriter(fn);
        file.write(obj.toJSONString());
        file.flush();
        file.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

//Print on console
    System.out.print(obj);
    }
Vasyl Lyashkevych
  • 1,920
  • 2
  • 23
  • 38
  • The OP is asking for Gson, not org.json. – Lyubomyr Shaydariv Apr 24 '17 at 19:03
  • I am sorry for my inattention. Also, you can see here the examples of Gson when you need only it: http://stackoverflow.com/questions/5554217/google-gson-deserialize-listclass-object-generic-type?rq=1 – Vasyl Lyashkevych Apr 25 '17 at 09:21
  • "when you need only it" -- well, it depends: Gson supports streamed writers via `JsonWriter` so no in-memory JSON trees (composite JSON objects like `JsonElement`, `JsonObject`, etc) are even necessary. – Lyubomyr Shaydariv Apr 25 '17 at 09:27