需要帮助从Java中JSON格式的API响应定义变量吗
我正在开发一个程序,从PokeAPI调用一个随机API,并从响应中创建变量作为提示。实际上,我在从http响应创建变量时遇到了问题,尤其是在使用getJSONObject()方法时,因为我不知道要在括号中放什么。如果有人能告诉我如何从这些数据中定义变量,我将不胜感激。非常感谢。 下面是一个JSON数据示例
"id": 12,
"name": "butterfree",
"base_experience": 178,
"height": 11,
"is_default": true,
"order": 16,
"weight": 320,
"abilities": [
{
"is_hidden": true,
"slot": 3,
"ability": {
"name": "tinted-lens",
"url": "https://pokeapi.co/api/v2/ability/110/"
}
}
这是我的尝试
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
public class Main {
public static void main(String[] args) throws JSONException, IOException {
BufferedReader br;
Gson gson = new Gson();
Random random = new Random();
int randomPoke = random.nextInt(151)+1;
String line;
StringBuffer responseContent = new StringBuffer();
String pokeURL = "https://pokeapi.co/api/v2/pokemon/" + randomPoke;
URL url = new URL(pokeURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setReadTimeout(5000);
con.setConnectTimeout(5000);
int responseCode = con.getResponseCode();
System.out.println(responseCode);
if (responseCode > 299){
br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
while ((line = br.readLine()) != null){
responseContent.append(line);
}
br.close();
}else {
br = new BufferedReader(new InputStreamReader(con.getInputStream()));
while ((line = br.readLine()) != null) {
responseContent.append(line);
}
br.close();
}
String json = gson.toJson(responseContent);
JSONObject jo = new JSONObject(json.trim().charAt(0));
//JSONArray ja = new JSONArray();
boolean isDefault = jo.getJSONObject(json).getBoolean("is_default");
System.out.println(isDefault);
} ```
# 1 楼答案
有很多方法可以做到这一点,我有两个建议,我只使用GSON lib
首先
第二
我写了测试,也许会对你有更多帮助