2013-04-07 76 views
2

我有很多JSON的大文件裏面 例如:得到巨大的JSON文件3第一JSON對象與GSON

{ 
    "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 
} 

當然,我試圖用startsObject()更改reader.beginArray()。 我不想打開所有的文件.. 任何幫助嗎?

謝謝。

回答

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對象必須是一個數組裏面。

+0

謝謝你的作品 – AnthonyC 2013-04-07 08:25:44