【问题标题】:How can I print this type of JSON in Android? [duplicate]如何在 Android 中打印这种类型的 JSON? [复制]
【发布时间】:2017-08-19 11:57:56
【问题描述】:

如何在 Android 中打印这种类型的 JSON 对象?它在 jsonObject 中包含 jsonArray。

这是我的 PHP 文件输出:

           {
             "response": [
               { 
               "cat_id": "1",
               "cat_name": "abc",
                "cat_status": "1"
              },
              {
               "cat_id": "2",
               "cat_name": "abc",
               "cat_status": "1"
              },
              {
              "cat_id": "3",
              "cat_name": "abc",
              "cat_status": "1"



             }

             ]
             }

【问题讨论】:

  • 你想在 logcat 中打印吗?如果是这样,请尝试Log.d()

标签: php android json


【解决方案1】:

试试这个

首先获取您的 JSONArray,如下所示

JSONObject json = new JSONObject(JsonResponseString);// get JSONObject from respones 
JSONArray jArray = json.getJSONArray("response");   // get JSONArray from json object

现在像下面的代码一样从 jsonArray 获取数据

for(int i=0; i<jArray.length(); i++){

  JSONObject json_data = jArray.getJSONObject(i);           // get your json object from array

  Log.d("cat_id", json_data.getString("cat_id"));          // get your cat_id

  Log.d("cat_name", json_data.getString("cat_name"));     // get your cat_name

  Log.d("cat_status", json_data.getString("cat_status"));// get your cat_status

}

【讨论】:

  • 谢谢它的工作
【解决方案2】:

使用这个:

Log.d("Data", obj.toString());

【讨论】:

  • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
【解决方案3】:

你需要把它放在一个 String 类型的变量中,比如说 responseString 而不是按照代码进行操作

    JSONObject  jsonRootObject = new JSONObject(responseString);
    JSONArray jsonArray = jsonRootObject.optJSONArray("response");
    String result = "", cat_id = "", cat_name = "", cat_status = ""; 
    for(int i=0; i < jsonArray.length(); i++){  

                            JSONObject jsonObject = jsonArray.getJSONObject(i);  
                            cat_id = jsonObject.optString("cat_id").toString();
                            cat_name = jsonObject.optString("cat_name").toString();
                            cat_status = jsonObject.optString("cat_status").toString();

    result += cat_id+"\n"+cat_name+"\n"+cat_status+"\n";                           
    }
textView_to_display_data_on_screen.setText(result);

它会将您的所有数据打印到 textView(即此处 textView_to_display_data_on_screen)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多