java - 需要帮助从 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);
} ```
解决方案
有很多方法可以做到这一点我有两个建议,我只使用 GSON lib
第一的
JsonElement element = JsonParser.parseString(json);
第二
new Gson().fromJson(json, LinkedTreeMap.class);
我写了测试,也许它会帮助你更多
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.internal.LinkedTreeMap;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class PokemonTest {
@Test
public void parserWithJsonParser() {
//given
String json = getJson();
Boolean isDefault = null;
//when
JsonElement element = JsonParser.parseString(json);
if (element.isJsonObject()) {
JsonObject asJsonObject = element.getAsJsonObject(); // is your Object
JsonElement element1 = asJsonObject.get("is_default");
if (element1.isJsonPrimitive()) {
isDefault = element1.getAsBoolean();
}
}
//then
assertTrue(isDefault);
}
@Test
public void parserWithMapOfObject() {
//given
String json = getJson();
//when
LinkedTreeMap<String, Object> linkedTreeMap = new Gson().fromJson(json, LinkedTreeMap.class);
Boolean isDefault = (Boolean) linkedTreeMap.get("is_default");
//then
assertTrue(isDefault);
}
public String getJson() {
return "{\n" +
" " +
"\"id\": 12,\n" +
" \"name\": \"butterfree\",\n" +
" \"base_experience\": 178,\n" +
" \"height\": 11,\n" +
" \"is_default\": true,\n" +
" \"order\": 16,\n" +
" \"weight\": 320,\n" +
" \"abilities\": [\n" +
" {\n" +
" \"is_hidden\": true,\n" +
" \"slot\": 3,\n" +
" \"ability\": {\n" +
" \"name\": \"tinted-lens\",\n" +
" \"url\": \"https://pokeapi.co/api/v2/ability/110/\"\n" +
" }\n" +
" }\n" +
" ]\n" +
"}";
}
}
推荐阅读
- firebase - 无法从 Firebase 存储中获取实际的字符串下载 url,并且只返回“未来的实例”
' 甚至使用 async/await - javascript - Passport JS 和自定义 async/await 函数
- java - 等待电子邮件
- sql - 由 CSV 支持的 Flink SQL 表,带有标题
- spring - 无法从可选加载配置数据:configserver:http//localhost:8012
- google-cloud-platform - 如何在大型查询计划作业上创建警报并在失败时发送电子邮件?
- java - 是否可以在 android studio 的可滚动视图中应用实时背景?
- xamarin.forms - 是否可以在运行时替换/修改隐式样式 xamarin 表单
- java - 如何在java中找到字符串的总和
- jquery - 填充使用 jquery 动态添加的选择列表