【问题标题】:How to find specific data from a Volley Api string response如何从 Volley Api 字符串响应中查找特定数据
【发布时间】:2019-12-09 16:22:04
【问题描述】:

我是 API 新手,终于知道如何成功地从网站检索请求响应。问题是我完全不知道应该如何处理响应。我不知道如何访问响应中的某些值

这是我的 API Volley 代码

  RequestQueue requestQueue = Volley.newRequestQueue(this);
    String uri = Uri.parse("https://chicken-coop.p.rapidapi.com/games/Fortnite?platform=pc")
            .buildUpon()
            .build().toString();

    StringRequest stringRequest = new StringRequest(
            Request.Method.GET, uri, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            displayResults.setText("Response: " + response.substring(0,500));

        }

    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
             displayResults.setText( "" + error.toString());
        }

    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("X-RapidAPI-Key", "5cdb2bbe57mshd9242c8d3177cb3p16f2fbjsnd7c5829eb4ad");
            params.put("X-RapidAPI-Host", "chicken-coop.p.rapidapi.com");
            return params;
        }
    };
    requestQueue.add(stringRequest);

这是我收到的响应查询

“结果”:{10 项 “标题”:“堡垒之夜” “发布日期”:“2017 年 7 月 25 日” “描述”:“Epic Games 的下一个项目让你建造堡垒并阻止僵尸入侵。” “类型”:[... ]6项 "图片":"https://static.metacritic.com/images/products/games/5/c7eb46ceb7da9c72c5a95193e8621faf-98.jpg" “得分”:81 “开发商”:“史诗游戏” “发布者”:[... ]1 件 “评级”:“T” "alsoAvailableOn":[6 项 0: “iPhone/iPad” 1: “PlayStation 3” 2: “PlayStation 4” 3: “转变” 4: “Xbox 360” 5: “Xbox One”

如何从响应查询中找到显式值?我一直在网上寻找如何做到这一点,有很多不同的方法可以去做,我不知道该怎么做。例如,我怎样才能将 发布日期 放入它自己的文本框中?当我使用字符串响应时,我在网上看到的大多数示例都使用 JsonObjects

【问题讨论】:

  • 检查我的答案

标签: java api android-studio android-volley


【解决方案1】:

在您的 onResponse 方法中,您需要解析结果,以便提取所需的任何数据

public void onResponse(String response) {
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray jsonArray = jsonObject.getJSONArray("result");
             // toaccess to your json data 
                String title = jsonArray.getString("title");
                // your code 


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

【讨论】:

  • 谢谢。这不是我所做的 1/1,但你是对的,我需要将字符串转换为 json 对象并从那里开始。谢谢!
猜你喜欢
  • 2020-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-11
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多