我正在处理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);
}
感谢您的帮助。
答案 0 :(得分:2)
您可以使用Feign来完成。
我建议您创建Java类来表示JSON结构,该结构已定义为here
这是一个基本演示:
public class App {
public static void main(String[] args) {
KhanAcademyAPI khanAcademyAPI = Feign.builder()
.decoder(new GsonDecoder())
.logLevel(Logger.Level.HEADERS)
.target(KhanAcademyAPI.class, "http://www.khanacademy.org");
Topic root = khanAcademyAPI.tree();
root.children.forEach(topic1 -> System.out.println(topic1.slug));
Topic science = khanAcademyAPI.topic("science");
science.children.forEach(topic1 -> System.out.println(topic1.description));
}
public static class Topic {
String description;
boolean hide;
String slug;
List<Topic> children;
}
interface KhanAcademyAPI {
@RequestLine("GET /api/v1/topictree")
Topic tree();
@RequestLine("GET /api/v1/topic/{topic_slug}")
Topic topic(@Param("topic_slug") String slug);
}
}
我仅使用以下Maven依赖项: