【问题标题】:Extracting JSON from PHP on Android在 Android 上从 PHP 中提取 JSON
【发布时间】:2013-07-23 19:50:31
【问题描述】:

我已经尝试过并尝试过,但似乎无法深入了解它。这是PHP代码

$query = "SELECT `title` FROM `c2torsdb`.`pE_vacancies` WHERE active=1 LIMIT 2";
$result = mysql_query($query,$link) or die('Errant query:  '.$query);
/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = array('post'=>$post);
    }
  }
  /* output in necessary format */
  if($format == 'json') {
    header('Content-type: application/json, charset=utf-8');
    echo json_encode($posts);
  }

这是我的代码 sn-p

    HttpResponse response = httpclient.execute(httppost);
    String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
    JSONObject object = new JSONObject(jsonResult);

    //JSONArray innerobj = object.getJSONArray("post");
    String name = object.getString("title");
    //String name = name1.getString(0);

    Log.v("isurgeon", name);

    //String name = object.getString("posts");
    //String verion = object.getString("version");
    textView.setText(name + " - ");

这是 PHP 脚本的 JSON 输出:

[{"post":{"title":"Property Litigation Assistant Solicitor"}},{"post":{"title":"Trusts and Probate Practitioner"}}]

我只想要“标题”。

【问题讨论】:

  • 有什么问题?它会崩溃(请登录猫),还是什么?只是一个猜测:你的 JSON 响应是一个数组,所以 new JSONObject(jsonResult) 不能工作。请改用new JSONArray(jsonResult)

标签: php android arrays json


【解决方案1】:

老实说,我不熟悉 android,但我知道 JSON。如果我要获取您的 JSON 输出并将其放入 javascript 中,如下所示:

var abc = [{"post":{"title":"Property Litigation Assistant Solicitor"}},{"post":{"title":"Trusts and Probate Practitioner"}}]

我会通过这样做获得第一个标题:

abc[0].title

你需要选择返回的json对象的第n个元素THEN获取标题。

【讨论】:

    【解决方案2】:

    Bill 是对的 - 你的 JSON 在那里输出的方式,所有内容都包含在一个数组中

    Android imo 对 JSON 对象/数组有非常好的原生处理,所以如果你只是这样做

    JSONArray jsonArray = new JSONArray(jsonResult);
    
    JSONObject object = jsonArray[0];
    

    一切正常

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      • 2015-08-22
      • 2014-07-08
      • 2019-09-13
      相关资源
      最近更新 更多