1

我正在使用的数据的 URL:https ://www.googleapis.com/youtube/v3/videos?part=snippet%2Cstatistics&chart=mostPopular&maxResults=50®ionCode=AU&videoCategoryId=15&key= {YOUR_API_KEY}

我目前正在开发这个可以检测 YouTube 热门话题的 Intelli J Java 命令行应用程序。但是,在编写一些尝试将 YouTube 数据字符串解析为 Video 对象的代码时,我需要帮助。这是我已经完成的一些代码,但不确定它是否适合对 YouTube 数据字符串进行解析:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;

public class YouTubeTrender {

    public static void test1() throws FileNotFoundException {

        System.out.println("Performing Test 1");
        String filename = "data/youtubedata_15_50.json";
        int expectedSize = 50;

        System.out.println("Testing the file: " + filename);
        System.out.println("Expecting size of: " + expectedSize);

        // Read data
        JsonReader jsonReader = Json.createReader(new FileInputStream(filename));
        JsonObject jobj = jsonReader.readObject();

        // read the values of the item field
        JsonArray items = jobj.getJsonArray("items");

        System.out.println("Size of input: " + items.size());
        System.out.println("Sucess: " + (expectedSize == items.size()));


    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException {
        System.out.println("YouTube Trender Application");

        test1();

    }
}

在我忘记这里的代码之前,我应该提一下,上面导入部分中的 JsonReader、JsonObject、Json.createReader、readObject、JsonArray、getJsonArray、json 都是红色文本作为错误,还有一些希望我创建一个类.

4

1 回答 1

0

您可以使用名为 Jackson 的库将 JSON 字符串转换为类。首先,你必须导入这个库。如果您使用的是 Maven,则可以添加:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

然后你必须创建你的Video类来保存数据。Jackson 将 JSON 字符串的每个键映射到具有相同名称的类字段。例如:

{
    "hello": "hi",
    "name": "alex"
}

然后,如果您将该 JSON 映射到一个名为 Greeting 的类:

public class Greeeting {
    private String hello;
    private String name;

    // The class must have getters and setters
    public String getHello() {
        return this.hello;
    }

    public String getName() {
        return this.name;
    }

    public void setHello(String hello) {
        this.hello = hello;
    }

    public void setName(String name) {
        this.name = name;
    }
}

如果将字符串映射到 Greeting.class,则会创建一个包含hiin hellofield 和alexin namefield 的 Greeting 实例。

要进行此映射,您可以执行以下操作:

public Greeting parseGreeting(String json) {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readValue(json, Greeting.class);
}

除了字符串,您还可以将文件作为第一个参数传递。

现在您必须Video.class根据 JSON 具有的字段来实现您的。

于 2020-04-30T14:08:51.487 回答