Search code examples
javaandroidjsongsonjson-deserialization

Why am I getting a JsonSyntaxException here?


I am experiencing a JSON parsing error. My code is as follows:

try {
        //Read the server response and attempt to parse it as JSON
        Reader reader = new InputStreamReader(content);

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat("M/d/yy hh:mm a");
        Gson gson = gsonBuilder.create();

        List<JsonObject> posts = (List) gson.fromJson(reader, JsonObject.class);

        Log.e(TAG, "Results Size: " + posts.size());

        //  for(int i=0; i<posts.size(); i++){
        //      Log.e(TAG, "Checking: " + posts.get(i).title());
        //  }

        content.close();

} catch (Exception ex) {
    Log.e(TAG, "Failed to parse JSON due to: " + ex);
}

I get the following error from my posts.size() check:

Failed to parse JSON due to: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2

For the JSON I am trying to read, if successful my posts.size() should be returning 5.

What am I doing wrong here?


Solution

  • I think your problem stems from the fact that you're trying to deserialize to a generic type (a List). The documentation states that in this case you need to pass in a Type rather than a Class to the fromJson() method. Try this:

    Type type = new TypeToken<List<JsonObject>>(){}.getType();
    List<JsonObject> posts = gson.fromJson(reader, type);