在Java中,如何访问JSON中的协助或杀手锏?
我试图使用pubgapi(流行的PC游戏),但在使用JSON时遇到了麻烦(第一次)。我只想访问进一步嵌入JSON数组中的数字 我曾尝试访问JSON数组的索引号,但似乎不起作用 下面是我试图使用的JSON !![1] :“json” 这是我试过的在Java中,如何访问JSON中的协助或杀手锏?,java,json,api,Java,Json,Api,我试图使用pubgapi(流行的PC游戏),但在使用JSON时遇到了麻烦(第一次)。我只想访问进一步嵌入JSON数组中的数字 我曾尝试访问JSON数组的索引号,但似乎不起作用 下面是我试图使用的JSON !![1] :“json” 这是我试过的 public static void main(String[] args) { StringBuffer response = new StringBuffer(); try { URL url = new
public static void main(String[] args) {
StringBuffer response = new StringBuffer();
try {
URL url = new URL("https://api.pubg.com/shards/steam/seasons/lifetime/gameMode/squad-fpp/players?filter[playerIds]=account.0165929b76b147d1a453bbfd21a58b4b");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
conn.setRequestProperty("Accept", "application/vnd.api+json");
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("============");
System.out.println("============");
JSONObject myResponse = new JSONObject(response.toString());
JSONArray arr = myResponse.getJSONArray("data");
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("type");
System.out.println("name: " + post_id);
}
}
publicstaticvoidmain(字符串[]args){
StringBuffer响应=新的StringBuffer();
试一试{
URL=新URL(“https://api.pubg.com/shards/steam/seasons/lifetime/gameMode/squad-fpp/players?filter[playerIds]=账户0165929b76b147d1a453bbfd21a58b4b”);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod(“GET”);
conn.setRequestProperty(“授权”、“承载人”+API_密钥);
conn.setRequestProperty(“接受”、“应用程序/vnd.api+json”);
BufferedReader in=新的BufferedReader(
新的InputStreamReader(conn.getInputStream());
字符串输入线;
响应=新的StringBuffer();
而((inputLine=in.readLine())!=null){
追加(inputLine);
}
in.close();
}捕获(格式错误){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
System.out.println(“======================”);
System.out.println(“======================”);
JSONObject myResponse=新的JSONObject(response.toString());
JSONArray arr=myResponse.getJSONArray(“数据”);
对于(int i=0;i
为什么它看起来不起作用,你得到了什么?我强烈建议调查任何数量的Java REST客户端(我倾向于使用Spring RestTemplate);任何合适的方法都会将整个网络部分缩减为两行(一行用于设置授权头,一行用于执行请求),Jackson或Gson会将JSON解析为Java对象(大多数REST库会自动为您处理)。