英文:
Need help defining variables from JSON formatted API response in Java
问题
我正在开发一个程序,该程序从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.Gson;
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 = responseContent.toString();
JSONObject jo = new JSONObject(json);
boolean isDefault = jo.getBoolean("is_default");
System.out.println(isDefault);
}
}
英文:
I'm working on a program that calls a random API from PokeAPI and creates variables from the response for use as hints. I'm having problems with actually creating variables from the http response especially with the getJSONObject() method because I don't know what to put in the parenthesis. If anyone could show me how to define variables from this data, i would appreciate it. Thank You.
here is an example of the JSON data
"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/"
}
}
and here is my attempt
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);
} ```
</details>
# 答案1
**得分**: 0
```java
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 "{" +
"\"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/\"" +
"}" +
"}" +
"]" +
"}";
}
}
英文:
there are many ways to do this I have two proposals and I use only GSON lib
first
JsonElement element = JsonParser.parseString(json);
second
new Gson().fromJson(json, LinkedTreeMap.class);
I wrote the tests, maybe it'll help you more
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" +
"}";
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论