将YouTube数据字符串解析为视频对象

问题描述 投票:1回答:1

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

我目前正在开发此Intelli J Java命令行应用程序,该应用程序可以检测YouTube趋势主题。但是,在尝试将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如何都是红色文本,这是一个错误,还有一些我想如何创建一堂课。

java intellij-idea jsonp youtube-data-api javadoc
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字符串的每个键映射到具有相同名称的类Field。例如:

{
    "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,将创建Greeting的实例,其中包含hi字段中的helloalex字段中的name

要做此映射,您可以做:

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.