I want to read this JSON file with java using GSON library. I am new to using gson libray. someone please correct my code My JSON file looks like this:
{
"tableRows":[
{
"id":"100",
"mailContent":"Test mail content 123",
"sentiment":"0"
},
{
"id":"200",
"mailContent":"Test mail content 123",
"sentiment":"0"
},
{
"id":"300",
"mailContent":"Test mail content 123",
"sentiment":"0"
}
]
}
This is the java code I wrote to read this file:
import java.io.FileNotFoundException;
import java.io.FileReader;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonIOException;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.google.gson.JsonObject;
public class Sample {
public static void main(String[] args) {
JsonParser parser = new JsonParser();
try {
JsonElement jsontree = parser.parse(
new FileReader(
"/Users/kesavan-4688/Desktop/JSP-Eclipse/Sample/src/Demo/sample.json"
)
);
JsonElement je = jsontree.getAsJsonObject();
JsonArray ja = je.getAsJsonArray();
for (Object o : ja)
{
JsonObject person = (JsonObject) o;
String id = person.get("id").getAsString();
System.out.println(id);
String mail = person.get("mailcontent").getAsString();
System.out.println(mail);
String sentiment = person.get("sentiment").getAsString();
System.out.println(sentiment);
}
}
catch (JsonIOException e) {
e.printStackTrace();
} catch (JsonSyntaxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
But I get the following exception:
Exception in thread "main" java.lang.IllegalStateException: This is not a JSON Array.
at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:106)
at Demo.Sample.main(Sample.java:18)