Java库GSON作在线解析网页上的JSON

发布时间:2024年01月14日

用了获取SexPhoto API作为实例

import com.google.gson.Gson;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Gson gson = new Gson();
        try {
            URL url = new URL("https://sex.nyan.xyz/api/v2/");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            JsonData jsonData = gson.fromJson(new InputStreamReader(connection.getInputStream()), JsonData.class);

            System.out.println("Status: " + jsonData.getStatus());
            System.out.println("URL: " + jsonData.getUrl());

            List<JsonData.Data> dataList = jsonData.getData();
            for (JsonData.Data data : dataList) {
                System.out.println("PID: " + data.getPid());
                System.out.println("Page: " + data.getPage());
                System.out.println("Author: " + data.getAuthor());
                System.out.println("Title: " + data.getTitle());
                System.out.println("Upload Date: " + data.getUpload_date());
                System.out.println("Tags: " + data.getTags());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public class JsonData {
        private String status;
        private List<Data> data;
        private String url;

        public String getStatus() { return status; }
        public List<Data> getData() { return data; }
        public String getUrl() { return url; }

        public static class Data {
            private String pid;
            private String page;
            private String author;
            private String title;
            private String upload_date;
            private List<String> tags;

            public String getPid() { return pid; }
            public String getPage() { return page; }
            public String getAuthor() { return author; }
            public String getTitle() { return title; }
            public String getUpload_date() { return upload_date; }
            public List<String> getTags() { return tags; }
        }
    }
}

祝你在Java开发中一切顺利即😉

文章来源:https://blog.csdn.net/weixin_47353778/article/details/135577651
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。