【问题标题】:How to read response from a POST volley?如何读取 POST volley 的响应?
【发布时间】:2019-04-26 16:34:44
【问题描述】:

我真的是 android 的新手,我正在登录系统上工作,我正在使用 volley 发布数据..我遇到的问题是当我尝试阅读响应时.. .. 响应如下所示:

{"st":"no","Message":"错误"}

我正在尝试仅访问 st 或 message 有没有办法做到这一点?我试着做:

response[i] ----Array type exexted found 'org.json.JSONObject'

 JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, params, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) { 
                    Log.e(TAG, "Response: " + response.length());
                    for (int i = 0; i < response.length(); i++) {
                        Log.e(TAG, "Values: " + response);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace(); 
                }
            });

            Volley.newRequestQueue(this).add(jsonRequest);

【问题讨论】:

    标签: java android post android-volley


    【解决方案1】:

    你可以使用

    response.getString("Message")
    

    从给定的 JSON 中获取消息

    【讨论】:

    • 感谢您的回复...当我使用 thtat 时,我得到了错误“未处理的异常 org.json.jsonexception”任何想法
    • 请捕获该异常并粘贴消息
    • 兄弟,我觉得很愚蠢,我没有使用 try/catch 块.....现在工作正常......非常感谢您的帮助
    【解决方案2】:
     @Override
     public void onResponse(String response) {
        try {
               JSONObject api_response = new JSONObject(response);
               String message = api_response.getString("Message")
           } catch (JSONException e) {
                e.printStackTrace();           
           }
    

    捕获 json 异常很重要,以防响应字符串无法转换为 json 对象。然后使用 getString() 从创建的 json 对象中获取消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 2019-01-23
      • 1970-01-01
      相关资源
      最近更新 更多