来自服务器的JSON响应的一部分返回null:Android

时间:2017-06-17 07:51:05

标签: android arrays json android-json

我正在尝试从服务器获取数据,然后将其显示到应用程序中。 我有JSON数据,

{"COLUMNS":["TIMEID","BRANCHID","COMPANYID","MON_O","TUE_O","WED_O","THU_O","FRI_O","SAT_O","SUN_O","MON_C","TUE_C","WED_C","THU_C","FRI_C","SAT_C","SUN_C","CREATDATE"],"DATA":[[195,4,4,"09:00","09:00","09:00","09:00","09:00","Closed","Closed","16:30","16:30","16:30","16:30","16:30","Closed","Closed","May, 16 2017 08:16:12"]]}

当我访问url时,我获得了完整的JSON数据,但是当我从服务器记录相同的响应时,我没有得到JSON数据的DATA部分。

我的JAVA类实现是,

public static final String MON_O  = "MON_O";
public static final String TUE_O = "TUE_O";
public static final String WED_O = "WED_O";
public static final String THU_O = "THU_O";
public static final String FRI_O = "FRI_O";
public static final String SAT_O = "SAT_O";
public static final String SUN_O = "SUN_O";

public static final String MON_C = "MON_C";
public static final String TUE_C = "TUE_C";
public static final String WED_C = "WED_C";
public static final String THU_C = "THU_C";
public static final String FRI_C = "FRI_C";
public static final String SAT_C = "SAT_C";
public static final String SUN_C = "SUN_C";

public static final String JSON_ARRAY = "COLUMNS";

private void getData() {
String url =      context.getString(site_url)+"branch_time.cfc?method=branchtime&branchid=" +dBranchID;

StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {

    @Override
    public void onResponse(String response) {
        showJSON(response);
    }
},
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(context,error.getMessage().toString(),Toast.LENGTH_LONG).show();
            }
        });

RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}

private void showJSON(String response) {

String name = "";

try {
        JSONObject jsonObject = new JSONObject(response);
        JSONArray result = jsonObject.getJSONArray(JSON_ARRAY);
        Log.d("TAG", result.toString());

        name = result.getString(MON_O);
} catch (JSONException e) {
    e.printStackTrace();
}

 timeStatus.setText(name);
}

我正在尝试从服务器记录结果并获取以下内容,

  ["TIMEID","BRANCHID","COMPANYID","MON_O","TUE_O","WED_O","THU_O","FRI_O","SAT_O","SUN_O","MON_C","TUE_C","WED_C","THU_C","FRI_C","SAT_C","SUN_C","CREATDATE"]

响应的DATA部分为空,我只能得到COLUMNS值。 我不知道为什么会发生这种情况。请大家帮忙吗?

2 个答案:

答案 0 :(得分:1)

也许它是null因为你从来没有这样做才能正确获取数据

JSONArray companyData = jsonObject.getJSONArray("DATA");

您只获得了COLUMNS数组,并且数据不在该数组中。

另请注意,数据数组是数组中的数组

答案 1 :(得分:0)

COLUMNS的代码使用将是:

        JSONObject companyData = jsonObject.getJSONArray("COLUMNS");

DATA的代码使用将是:

        JSONObject companyData = jsonObject.getJSONArray("DATA ");

如果您得到所需的解决方案,请将我的答案标记为有用。