1

I've seen a lot of post about how to parse JSON files using Gson library, but they all use root elements in order to do the Serialization. So, in that case, you don't have the root element.

Example (persons.json)

[
{
    "name":"Paul",
    "telephone": 5434523542,
    "email": "paul@xd.com"
},
{
    "name":"William",
    "telephone": 23423520,
    "email": "aijda@fns.com"
}
]

The JSON file have more than 1000 objects as the two represented above.

I defined a class named Person, like

Person.java

public class Person {    
    private String name;
    private int phone;
    private String email;

    public Person(String name, int phone, String email) {
        this.name = name;
        this.phone = phone;
        this.email = email;
}

So now, I want to get all the information on my main class using Gson library. How can I do it without root element?

Steve Cole
  • 13
  • 5

2 Answers2

1

You have a List< Person > there. So this may do the trick:

Type listType = new TypeToken<ArrayList<Person>>(){}.getType();
List<Person> persons = new Gson().fromJson(jsonArray, listType);

Or as an array:

Person[] persons = gson.fromJson(jsonString, Person[].class);

Didn't tried on my PC, but should work. Let me know!

Josemy
  • 810
  • 1
  • 12
  • 29
0

I believe this question has already been asked (and answered) Gson and deserializing an array of objects with arrays in it

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    Person[] myTypes = gson.fromJson(new FileReader("input.json"), Person[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

public class Person {    
    String name;
    int phone;
    String email;
}
Irek L.
  • 316
  • 1
  • 6