【问题标题】:Reading PHP encoded array with Android用 Android 读取 PHP 编码的数组
【发布时间】:2015-12-13 12:53:09
【问题描述】:

我用 PHP 创建了一个数组。我需要帮助如何阅读它,使用 Android 应用程序。

编码数组如下所示:

["id","string 1","string 2","string 3","string 3","string 4"]

我必须能够通过 Android 应用程序读取它的所有元素。

它是用 PHP 创建的,代码如下:

    $res = array();
    $res[] = $data['id'];
    $res[] = $data['string 1'];
    $res[] = $data['string 2'];
    $res[] = $data['string 3'];
    $res[] = $data['string 4'];
    return json_encode($res);

你能帮我解决这个问题吗?

【问题讨论】:

  • 请发布您从 PHP 服务器获得的response 字符串。 (json_encode($res))
  • 这是响应:["id","string 1","string 2","string 3","string 3","string 4"]
  • 你确定吗?您是否尝试将其记录到控制台?因为json_encode 应该返回类似{ .. }
  • 这是我放 echo json_encode($res); 时返回的内容;而不是 return json_encode($res);
  • 我记得你应该使用echo...另外,你应该在Android客户端上记录它,而不是在后端。

标签: php android arrays json


【解决方案1】:

对于您的示例,您可以使用以下代码在 Android 中解析响应。我已经硬编码了你在代码中得到的响应,所以你明白了。我也把它写在我的活动的 onCreate 中,你可以在任何适合你的应用程序的地方写这个。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String strJson="[\"id\",\"string 1\",\"string 2\",\"string 3\",\"string 3\",\"string 4\"]"; // This is your response, with escaped " and used as a String

    try {

        //Get the instance of JSONArray that contains Strings
        JSONArray jsonArray = new JSONArray(strJson);
        for(int i=0; i < jsonArray.length(); i++){
            String data = (String)jsonArray.get(i);
            Log.d("MyData",data);
        }

    } catch (JSONException e) {e.printStackTrace(); // Not a good idea. But left it for now}
}

如果您使用过滤器 MyData 监控 logcat,您会发现输出为:

D/DATAIS: id
D/DATAIS: string 1
D/DATAIS: string 2
D/DATAIS: string 3
D/DATAIS: string 3
D/DATAIS: string 4

网络上有很多关于如何在 Android 中解析 JSON 的教程。您可以研究它们以获得更好的想法。

【讨论】:

    【解决方案2】:

    当我为 PHP 数组的元素添加名称时,我解决了这个问题:

    $res = array();
    $res[0] = $data['id'];
    $res[1] = $data['string 1'];
    $res[2] = $data['string 2'];
    $res[3] = $data['string 3'];
    $res[4] = $data['string 4'];
    

    在 Android 方面:

    JSONObject  mainObject = new JSONObject(ret);
    String str1 = mainObject.optString("1").toString();
    String str2 = mainObject.optString("2").toString();
    String str3 = mainObject.optString("3").toString();
    String str4 = mainObject.optString("4").toString();
    

    谢谢大家的帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-15
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多