有 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);
    } ```


共 (1) 个答案

  1. # 1 楼答案

    有很多方法可以做到这一点,我有两个建议,我只使用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" +
                "}";
      }
    }