简体   繁体   English

从RESTful API提取数据以解析为json并从那里提取数据

[英]Extracting data from RESTful API to parse as json and extract data from there JAVA

I am dealing with a pretty old API provided from KhanAcademy. 我正在处理KhanAcademy提供的一个很旧的API。

Link to git: https://github.com/Khan/khan-api/wiki/Khan-Academy-API 链接到git: https : //github.com/Khan/khan-api/wiki/Khan-Academy-API

I don't have any experience consuming REST services or how to parse Json from them. 我没有使用REST服务或如何从中解析Json的经验。 I have tried what I could find online but most SO posts or other things on the internet don't involve handling both REST and json at the same time. 我尝试了可以​​在网上找到的内容,但是大多数SO帖子或互联网上的其他内容都不涉及同时处理REST和json。 I have tried mapping the json to a map but I couldn't get that to work due to my Json queries not being processed properly. 我曾尝试将json映射到地图,但由于Json查询未正确处理,因此无法正常工作。

Here are some bits of code that I have tried using: 这是我尝试使用的一些代码:

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;
    }

the below is using JAX RS API 下面是使用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);

}

The below is some "Zombie code", it is a compilation of things I have tried mainly shown to verify that I am truly lost and that I have been looking for a solution for about 7 hours now? 下面是一些“僵尸代码”,它是我尝试过的一些事情的汇编,主要用来证明我确实迷路了,并且我一直在寻找解决方案大约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);
}

Any help is appreciated. 任何帮助表示赞赏。

You can use Feign to do it. 您可以使用Feign来做到这一点。

I recommend you create Java classes for representing the JSON structure, which is defined here 我建议您创建用于表示JSON结构的Java类,该类在此处定义

Here a basic demo: 这里是一个基本的演示:

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);
    }
}

I used the following maven dependencies only: 我仅使用以下Maven依赖项:

  • io.github.openfeign:feign-core:10.2.0 io.github.openfeign:feign-core:10.2.0
  • io.github.openfeign:feign-gson:10.2.0 io.github.openfeign:feign-gson:10.2.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM