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've tried using 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, in doing so, i found this error: java.lang.IllegalStateException: Not a JSON Object
at the second line.
Reading and writing JSON using GSON is very easy. You can use these two methods: toJSON() : It will convert simple pojo object to JSON string. FromJSON() : It will convert JSON string to pojo object.
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson is an open-source project hosted at http://code.google.com/p/google-gson.
You're trying to parse array to object, in which case you'll fail, because top level structure in your json is array.
I would parse this JSON in slightly different way
1) Create some 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 guess that solved your problem
Second way:
BufferedReader br = new BufferedReader(new FileReader(JSON_PATH));
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(br).getAsJsonArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With