需要帮助在Java中从JSON格式的API响应中定义变量。

huangapple go评论75阅读模式
英文:

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(&quot;is_default&quot;);
if (element1.isJsonPrimitive()) {
isDefault = element1.getAsBoolean();
}
}
//then
assertTrue(isDefault);
}
@Test
public void parserWithMapOfObject() {
//given
String json = getJson();
//when
LinkedTreeMap&lt;String, Object&gt; linkedTreeMap = new Gson().fromJson(json, LinkedTreeMap.class);
Boolean isDefault = (Boolean) linkedTreeMap.get(&quot;is_default&quot;);
//then
assertTrue(isDefault);
}
public String getJson() {
return &quot;{\n&quot; +
&quot;  &quot; +
&quot;\&quot;id\&quot;: 12,\n&quot; +
&quot;  \&quot;name\&quot;: \&quot;butterfree\&quot;,\n&quot; +
&quot;  \&quot;base_experience\&quot;: 178,\n&quot; +
&quot;  \&quot;height\&quot;: 11,\n&quot; +
&quot;  \&quot;is_default\&quot;: true,\n&quot; +
&quot;  \&quot;order\&quot;: 16,\n&quot; +
&quot;  \&quot;weight\&quot;: 320,\n&quot; +
&quot;  \&quot;abilities\&quot;: [\n&quot; +
&quot;    {\n&quot; +
&quot;      \&quot;is_hidden\&quot;: true,\n&quot; +
&quot;      \&quot;slot\&quot;: 3,\n&quot; +
&quot;      \&quot;ability\&quot;: {\n&quot; +
&quot;        \&quot;name\&quot;: \&quot;tinted-lens\&quot;,\n&quot; +
&quot;        \&quot;url\&quot;: \&quot;https://pokeapi.co/api/v2/ability/110/\&quot;\n&quot; +
&quot;      }\n&quot; +
&quot;    }\n&quot; +
&quot;  ]\n&quot; +
&quot;}&quot;;
}
}

huangapple
  • 本文由 发表于 2020年4月10日 12:13:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/61133940.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定