2012-10-06 18 views
0

我掙扎在transfering從JQuery的驗證碼到Java:在Java中實現REST API客戶端和JSON解析器的最簡單方法是什麼?

var url = 'http://gdata.youtube.com/feeds/api/videos/'; 

$.getJSON(url + '?v=2&alt=json-in-script&callback=?', { 
    'q': q, 
    }, function(data) {gotData(q, data);}); 

function gotData(q, data){ 
    for(var i in data.feed.entry){ 
    // print the data... 
    } 
} 

它調用的YouTube API和讀取一些JSON結果字段。

什麼是在Java中實現這個最簡單和最正確的方法?由於我只需要一個API方法調用,所以我需要最輕的解決方案。但我猜測在Java中,無論使用什麼庫,代碼都會變得更加複雜。

此外,我不想使用適用於Java的YouTube API客戶端,而是使用一些通用的REST-JSON解決方案,而未來我可以使用它來添加更多的API-s。

回答

0

我會使用google-gson Google Gson
它的註釋驅動,非常容易使用。

1

你可以使用Apache HttpClientJackson Json

DefaultHttpClient httpClient = new DefaultHttpClient(); 
// Add query string into get request 
HttpGet getRequest = new HttpGet("http://gdata.youtube.com/feeds/api/videos/"); 

getRequest.setHeader("Accept", "application/json"); 

HttpResponse response = httpClient.execute(getRequest); 

ObjectMapper mapper = new ObjectMapper(); 
Map<String, Object> jsonMap = mapper.readValue(response.getEntity().getContent(), new TypeReference<HashMap<String,Object>>() {}); 
相關問題