Reputation: 139
Trying to load a JSON file, getting an error but what does it mean?
public class MovieCollection{
private List<Movie> movies;
private Movie movie;
public MovieCollection() {
this.movies = new ArrayList<Movie>();
}
/**
* Creates a new book collection with the specified list of books pre-defined.
*
* @param books A books list.
*/
public MovieCollection(List<Movie> movies) {
this.movies= movies;
}
public static MovieCollection loadFromJSONFile (File file){
Gson gson = new Gson();
JsonReader jsonReader = null;
try {
jsonReader = new JsonReader(new FileReader(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Error");
}
return gson.fromJson(jsonReader, MovieCollection.class);
}
Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
Upvotes: 0
Views: 44
Reputation: 982
The error clearly says that the text you are trying to read is actually an array and not a JSON. It is an Array of JSON. This means you need some way of reading an array of objects like the one shown below:
Gson gson = new Gson();
User[] userArray = gson.fromJson(userJson, User[].class);
This allows you to read array of User objects from a json array text. Sample json for above code is included below.
[
{
"name": "Alex",
"id": 1
},
{
"name": "Brian",
"id": 2
},
{
"name": "Charles",
"id": 3
}
]
User class is defined as
public class User
{
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
Reference available at this link
Upvotes: 1