首页 > 解决方案 > 如何在 json 响应中获取值

问题描述

我需要在响应 api 帖子中获取值元素,我以 json 格式收到答案,以下是示例:

public void postJsonToServer() throws JSONException {
        JSONObject js = createJsonObject();
        String url = "http://link/User";
        JsonObjectRequest jsonObjReq = new JsonObjectRequest(com.android.volley.Request.Method.POST, url, js, new com.android.volley.Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, response.toString());
                try {
                    String as = response.getString("Planta");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

回复:

{"Codigo":200,"Mensaje":"Usuario validado","Nombre":"Luis Smith","ClaveNom":"9633","Planta":"SIN","Indicador":"","Listado":""}

如何获得元素Planta和Indicador?

下一行返回null,我不知道还能做什么,请帮帮我。

 String as = response.getString("Planta");

谢谢

标签: androidjson

解决方案


你可以试试

try {
   JSONObject responseOBJ = new JSONObject(String.valueOf(response));
   if(responseOBJ.has(responseOBJ.getString("Planta"))
   {
     String as = responseOBJ.getString("Planta");
   }
   
} catch (JSONException e) {
    e.printStackTrace();
}

推荐阅读