1

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?

4

2 回答 2

1

我认为您的问题源于您试图反序列化为泛型类型(a List)的事实。文档指出,在这种情况下,您需要将 aType而不是 a传递Class给该fromJson()方法。尝试这个:

Type type = new TypeToken<List<JsonObject>>(){}.getType();
List<JsonObject> posts = gson.fromJson(reader, type);
于 2013-09-08T00:28:14.880 回答
0

正如它在异常行中提到的那样,您的JSON开头是[所以它表示 aJSON Array而不是 a JSON Object,但JSON必须以 a 开头JSON Object。所以用情侣包装你的JSON文件(在开头和结尾添加)。它应该可以解决问题。{ }{}

于 2013-09-08T00:03:45.687 回答