好吧,我咬一口:
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonStructure;
import javax.json.JsonValue;
public class StackOverflow44316515{
public static void main(final String[] args) throws Exception{
final StackOverflow44316515 example = new StackOverflow44316515();
// Get data:
final JsonObject jsonLangObjs = example.getLanguages("java");
// Copy items into a mutable array:
final JsonArray items = jsonLangObjs.getJsonArray("items");
final JsonObject[] itemsArray = items.toArray(new JsonObject[items.size()]);
// Sort the array:
Arrays.sort(itemsArray, new Comparator<JsonValue>(){
@Override
public int compare(final JsonValue o1, final JsonValue o2){
return ((JsonObject)o1).getString("created_at")
.compareTo(((JsonObject)o2).getString("created_at"));
}
});
// Re-wrap in a list API for convenience (optional):
final List<JsonObject> itemsArrayList = Arrays.asList(itemsArray);
// Print sample:
for(final JsonObject jo : itemsArrayList){
System.out.println(jo.getString("created_at") + " - " + jo.getString("full_name"));
}
}
public JsonObject getLanguages(final String language) throws Exception{
final URL url = new URL("https://api.github.com/search/repositories?q=language:"
+ URLEncoder.encode(language, "UTF-8")
+ "&per_page=10");
final HttpURLConnection huc = (HttpURLConnection)url.openConnection();
if(huc.getResponseCode() != 200){
throw new Exception("Error calling web service: "
+ huc.getResponseCode() + " - " + huc.getResponseMessage());
}
try(final InputStream is = huc.getInputStream()){
final JsonStructure json = Json.createReader(is).read();
return (JsonObject)json;
}
}
}
输出:
2010-02-08T13:20:56Z - elastic/elasticsearch
2010-09-06T21:39:43Z - square/retrofit
2012-07-23T13:42:55Z - square/okhttp
2013-01-08T20:11:48Z - ReactiveX/RxJava
2013-03-05T08:18:59Z - JakeWharton/butterknife
2013-07-08T22:52:33Z - bumptech/glide
2014-04-25T14:29:47Z - PhilJay/MPAndroidChart
2014-05-29T16:23:17Z - google/guava
2014-08-09T16:45:18Z - iluwatar/java-design-patterns
2015-04-29T23:54:16Z - square/leakcanary
ISO-8601 格式的日期幸运地按照它们的字典顺序正确排序 - 所以对于这样一个简单的练习,我们甚至不需要首先将它们解析为 Java 数据对象等。
在此处记下 GitHub 的服务器端分页 - 有必要不要一次将所有 3.2+ 百万个结果淹没您。对于本示例,我将默认的 30 个结果限制为 10 个。如果您确实需要分析所有结果,我将把它作为练习留给读者。 https://developer.github.com/v3/guides/traversing-with-pagination/ 对此有一些额外的细节。
此示例代码假定所有记录始终存在 created_at 值。除非这是 GitHub 的 API 保证(即使如此),都应该在此处为生产代码添加额外的检查。
注意语言参数的 URL 编码,以帮助防止注入攻击(假设“语言”参数不受信任)。
注意使用 Java 的内置 java.net 类 - 这里不需要第 3 方 HTTP 库。
请注意,此代码不会捕获任何它无法处理的异常。一个空的 catch 块,甚至一个只输出异常的 catch 块几乎总是对任何人都没有好处。 (“好的,现在怎么办?”)即,您真的希望代码继续执行,就好像没有发生任何不好的事情一样?
此代码还将每组 JSON 结果构建到内存中对象模型中(JsonArray 或 JsonObjects)。虽然这里的示例最简单,但更有效的实现将利用流接口,例如JsonParser。另见: