【发布时间】:2019-04-02 23:46:48
【问题描述】:
我正在处理 KhanAcademy 提供的一个相当旧的 API。
git 链接:https://github.com/Khan/khan-api/wiki/Khan-Academy-API
我没有任何使用 REST 服务或如何从中解析 Json 的经验。我已经尝试了我可以在网上找到的东西,但是互联网上的大多数 SO 帖子或其他东西并不涉及同时处理 REST 和 json。 我已尝试将 json 映射到地图,但由于我的 Json 查询未正确处理,我无法使其正常工作。
以下是我尝试使用的一些代码:
public static Object getConnection(String url){
URL jsonUrl;
String message;
try{
jsonUrl = new URL(url);
System.out.println("This is the URL: "+ jsonUrl);
} catch (MalformedURLException ex) {
message = "failed to open a new conenction. "+ ex.getMessage();
//logger.warn(message);
throw new RuntimeException();
}
URLConnection connection;
try{
connection = jsonUrl.openConnection();
connection.connect();
}catch(IOException e){
message = "Failed to open a new connection. " + e.getMessage();
//logger.warn(message);
throw new RuntimeException();
}
Object jsonContents;
try{
jsonContents = connection.getContent();
System.out.println("This is the content: "+jsonContents);
}catch(IOException e){
message = "failed to get contents.";
//logger.warn(message);
throw new RuntimeException(message);
}
return jsonContents;
}
以下是使用 JAX RS API
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://www.khanacademy.org/api/v1/topictree");
JsonArray response = target.request(MediaType.APPLICATION_JSON).get(JsonArray.class);
}
下面是一些“僵尸代码”,它是我尝试过的东西的汇编,主要是为了验证我真的迷路了,我已经寻找解决方案大约 7 个小时了?
JsonReader reader = new JsonReader(response);
JsonParser parser = new JsonParser();
JsonElement rootElement = parser.parse(reader);
JsonElement rootElement = parser.parse(response.getAsString());
JsonArray jsonArray = rootElement.getAsJsonArray();
ArrayList results = new ArrayList();
Gson myGson = new Gson();
for(JsonElement resElement : jsonArray){
//String mp4 = myGson.fromJson(resElement, );
}
JsonArray jarray =jsonObject.getAsJsonArray();
jsonObject= jarray.get(0).getAsJsonObject();
String result = jsonObject.get("title").getAsString();
System.out.println(result);
JsonObject resultObject = jsonObject.getAsJsonObject("url");
String result = resultObject.getAsString();
System.out.println(result);
JsonObject jsonObject=response.get(0).getAsJsonObject();
return new Gson().fromJson(url, mapType);
}
感谢任何帮助。
【问题讨论】:
-
API调用后你想从json结果中提取什么?
-
@Karan 嗨,Karan,感谢您的回复。如果我可以告诉你这个:[链接]api-explorer.khanacademy.org/api/v1/topic[link]。我想获取用户选择的主题/主题的所有 youtube 链接/mp4 url。我最初将浏览器指向 [link]khanacademy.org/api/v1/topic[link]/
。问题可能在于我不知道如何处理解析的 json。我还发现按主题搜索通常意味着没有结果,所以我尝试指向这个:[link]khanacademy.org/api/v1/topictree[link]