2011-10-04 87 views
4

我想解析來自MongoDB雲服務器的數據。從服務器返回的json數據如下:如何使用GSON解析這個JSON數據?並把它放入一個ArrayList

[ 
{ 
    "_id": { 
     "$oid": "4e78eb48737d445c00c8826b" 
    }, 
    "message": "cmon", 
    "type": 1, 
    "loc": { 
     "longitude": -75.65530921666667, 
     "latitude": 41.407904566666666 
    }, 
    "title": "test" 
}, 
{ 
    "_id": { 
     "$oid": "4e7923cb737d445c00c88289" 
    }, 
    "message": "yo", 
    "type": 4, 
    "loc": { 
     "longitude": -75.65541383333333, 
     "latitude": 41.407908883333334 
    }, 
    "title": "wtf" 
}, 
{ 
    "_id": { 
     "$oid": "4e79474f737d445c00c882b2" 
    }, 
    "message": "hxnxjx", 
    "type": 4, 
    "loc": { 
     "longitude": -75.65555572509766, 
     "latitude": 41.41263961791992 
    }, 
    "title": "test cell" 
} 

]

我遇到的問題是恢復不包括JSON對象數組的名稱的數據結構。每個返回的對象都是一個「帖子」。但是,如果沒有JSON對象數組的名稱,我該如何使用GSON解析它。我想將這些「帖子」放入Post類型的ArrayList中。

回答

13

的代碼,你一塊正在尋找:

String jsonResponse = "bla bla bla"; 
Type listType = new TypeToken<List<Post>>(){}.getType(); 
List<Post> posts = (List<Post>) gson.fromJson(jsonResponse, listType); 
+0

這應該是公認的答案。 Sam_D的答案有效,但這段代碼看起來要快得多,而且在較大的JSONArray上可能會引人注意。 – Matt

+0

是的,處理大json – Patrick

+0

太棒了!你能解釋它是如何工作的嗎?第2和第3行 – oyatek

1

使用JSONArray的構造器解析字符串:

//optionally use the com.google.gson.Gson package 
Gson gson = new Gson(); 
ArrayList<Post> yourList = new ArrayList<Post>(); 
String jsonString = "your string"; 
JSONArray jsonArray = new JSONArray(jsonString); 
for (int i = 0; i < jsonArray.length(); i++){ 
    Post post = new Post(); 

    //manually parse for all 5 fields, here's an example for message 
    post.setMessage(jsonArray.get(i).getString("message")); 

    //OR using gson...something like this should work 
    //post = gson.fromJson(jsonArray.get(i),Post.class); 

    yourList.Add(post); 
} 

考慮到只有5場,使用GSON可能比你需要更多的開銷。

+0

好吧,我不打算增加更多的領域我的項目繼續 –