使用gson从巨大的json文件中获取3个第一个json对象

时间:2013-04-07 05:46:16

标签: java json gson

我有一个包含大量json的大文件 例如:

{
   "id":1,
   "text":"foo the bar",
   ...
},
{
   "id":2,
   "text":"foo the bar",
   ...
},
{
   "id":3,
   "text":"foo the bar",
   ...
},
{
   "id":4,
   "text":"foo the bar",
   ...
},...

我想只使用3个第一个对象,我尝试了这个代码,但是我得到了一个异常“不是有效的json格式”。

JsonReader reader = new JsonReader( new FileReader(path) );
reader.beginArray();
int i = 0;
while (reader.hasNext() && i < 3) {
    JsonParser  _parser = new JsonParser();
    JsonElement jsonElement =  _parser.parse(reader);
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    //Do something
}

当然我试图用beginObject()改变我的reader.beginArray()。 我也不想打开所有文件.. 有什么帮助吗?

感谢。

1 个答案:

答案 0 :(得分:0)

就像消息所说它不是一个有效的json格式。看起来应该是这样的

[{
   "id":1,
   "text":"foo the bar",
   ...
},
{
   "id":2,
   "text":"foo the bar",
   ...
},
{
   "id":3,
   "text":"foo the bar",
   ...
},
{
   "id":4,
   "text":"foo the bar",
   ...
},...]

json对象必须位于数组中。