21xrx.com
2025-04-01 04:11:34 Tuesday
文章检索 我的文章 写文章
Java通过API调用返回JSON数据结构
2023-06-15 17:30:06 深夜i     28     0
Java API JSON 解析 序列化

Java是一种广泛使用的编程语言,拥有强大的类库和API,可以方便的与其他系统互操作。当我们需要从其他系统获取数据时,通常会使用API接口进行交互。在这个过程中,返回的数据类型多种多样。其中比较流行的一种数据结构是JSON。

JSON是一种轻量级的数据交换格式,易于阅读和编写,同时适用于各种编程语言。在Java中,我们可以通过一些开源库来对JSON进行解析和序列化,例如Gson和Jackson。

在使用Java调用API时,需要先通过URL和HTTP协议进行连接。收到响应后,再将返回的数据进行解析。可以通过JSONObject和JSONArray来对JSON数据进行解析。

下面是一个使用Java从GitHub API获取仓库列表的示例代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;
public class GitHubAPIExample {
  public static void main(String[] args) throws Exception {
    String url = "https://api.github.com/users/octocat/repos";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
    }
    in.close();
    JSONArray jsonArray = new JSONArray(response.toString());
    for (int i = 0; i < jsonArray.length(); i++) {
      JSONObject jsonObject = jsonArray.getJSONObject(i);
      String name = jsonObject.getString("name");
      String language = jsonObject.getString("language");
      String description = jsonObject.getString("description");
      System.out.println(name + " (" + language + "): " + description);
    }
  }
}

该示例代码中,首先建立GitHub API的URL,然后通过HttpURLConnection对象进行连接,通过getInputStream()方法获取返回的JSON数据,并将其转换成JSONArray对象。最后遍历JSONArray,获取每个仓库的名称、主要语言和描述信息。

本文介绍了Java调用API并返回JSON数据的基本过程和示例代码。

  
  

评论区