为什么我在这里得到JsonSyntaxException?

时间:2013-09-07 23:43:36

标签: java android json gson json-deserialization

我遇到了JSON解析错误。我的代码如下:

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);
}

我从posts.size()支票中收到以下错误:

  

由于以下原因导致无法解析JSON:com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期为BEGIN_OBJECT但在第1行第2列为BEGIN_ARRAY

对于我想要阅读的JSON,如果成功,我的posts.size()应该返回5。

我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

正如在异常行中提到的那样,JSON[开头,因此它表示JSON Array而不是JSON Object,但JSON必须以JSON Object开头。因此请将JSON文件与{ }对包裹起来(在开头添加{,在}结束)。它应该解决这个问题。