Read json file using gson library

I have a json file formatted as the following:

[{ 'title': 'Java', 'authors': ['Auth', 'Name'] }, { 'title': 'Java2', 'authors': ['Auth2', 'Name2'] }, { 'title': 'Java3', 'authors': ['Auth3', 'Name3'] }] 

So, I tried to use the gson library to parse the file with the following code:

 JsonElement jelement = new JsonParser().parse(pathFile); JsonObject jObject = jelement.getAsJsonObject(); JsonArray jOb = jObject.getAsJsonArray(""); final String[] jObTE = new String[jOb.size()]; for (int k=0; k<jObTE.length; k++) { final JsonElement jCT = jOb.get(k); JsonObject jOTE = jCT.getAsJsonObject(); JsonArray jContentTime = jOTE.getAsJsonArray("content_time"); final String[] contentTime = new String[jContentTime.size()]; for (int i=0; i<contentTime.length; i++) { final JsonElement jsonCT = jContentTime.get(i); JsonObject jObjectTE = jsonCT.getAsJsonObject(); JsonArray jTE = jObjectTE.getAsJsonArray(""); final String[] contentTimeTE = new String[jTE.size()]; for (int j=0; j<contentTimeTE.length; j++) { final JsonElement jsonCTTE = jTE.get(j); contentTime[j] = jsonCTTE.getAsString(); } } } 

But at the same time, I found this error: java.lang.IllegalStateException: Not a JSON Object in the second line.

+7
java json file gson
source share
1 answer

You are trying to parse an array into an object, in which case you will fail because the top level structure in your json is an array.

I would analyze this JSON a little differently.

1) Create a Model class

 public class Model { private String title; private List<String> authors; //getters ... } 

2) Parse your JSON (

 public static final String JSON_PATH = "/Users/dawid/Workspace/Test/test.json"; Gson gson = new Gson(); BufferedReader br = new BufferedReader(new FileReader(JSON_PATH)); Type type = new TypeToken<List<Model>>(){}.getType(); List<Model> models = gson.fromJson(br, type); 

Your code is barely readable, so I assume I solved your problem.

The second way:

 BufferedReader br = new BufferedReader(new FileReader(JSON_PATH)); JsonParser parser = new JsonParser(); JsonArray array = parser.parse(br).getAsJsonArray(); 
+9
source share

All Articles