如何通过JSON将PHP的输出转换为解析数据

时间:2015-10-29 17:34:41

标签: php android arrays json

我在webhost上有以下php文件正常工作。

<?php
   $dbhost = 'dbhost';
   $dbuser = 'dbuser';
   $dbpass = 'pass';

   $conn = mysql_connect($dbhost, $dbuser, $dbpass);

   if(! $conn )
   {
      die('Could not connect'.mysql_error());
   }

   $sql = "SELECT FIELD1, FIELD2, FIELD3, FIELD4 FROM `TABLE` WHERE FIELD1 =     'VALUE1' ";
   mysql_select_db('MyDB');
   $retval = mysql_query( $sql, $conn );

   if(! $retval )
   {
      die('Could not get data: ' . mysql_error());
   }

   while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
   {
      echo "FIELD1" :{$row['FIELD1']}  <br> ".
         "FIELD2 : {$row['FIELD2']} <br> ".
         "FIELD3 : {$row['FIELD3']} <br> ";
      $output[] = $row;
   }

   print(json_encode($row));
   mysql_close($conn);
?>

链接在这里http://marcodr.byethost7.com/TP2.php

现在,我想在TextView中显示此内容,但我使用以下代码失败了

JSONObject object=getJSONObject(“result”); //comes from the     print(json_encode ($result));
JSONArray arr=object.getJSONArray(“Value1”); //transforms the object Value1 in array
for(int i=0;i<arr.length;i++){
JSONObject obj1=arr.getJSONObject(i);
String Value1=obj1.getString("Value1");
TextView.setText(Value1); //set TextView’s content to the String Value1
}

清单有权导航互联网,文本视图在布局等,但仍然不能把PHP输出放在TextView中。我的代码出了什么问题?

2 个答案:

答案 0 :(得分:0)

在PHP方面:

$obj = new stdClass();
$obj->label="Price of an item";
$obj->data = array(
    array('1999','200'),
    array('2000','210'),
    array('2007','240')
);

echo json_encode($obj);

假设您的JSON是这样的:

[
    {
        "response": [
            {
                "1999": "200",
                "2000": "210",
                "2007": "240"
            }
        ]
    }
]

在Android方面:

String jsonString3 =
                "[\n" +
                        "    {\n" +
                        "        \"response\": [\n" +
                        "            {\n" +
                        "                \"1999\": \"200\",\n" +
                        "                \"2000\": \"210\",\n" +
                        "                \"2007\": \"240\"\n" +
                        "            }\n" +
                        "        ]\n" +
                        "    }\n" +
                        "]";
        try{
            JSONArray array = new JSONArray(jsonString3);
            JSONArray priceArray = array.getJSONObject(0).getJSONArray("response");
            Log.d(LOG_TAG,"Price Array = " + priceArray.toString());

            for (int i = 0; i < priceArray.length(); i++){
                Log.d(LOG_TAG, "1999 = " + priceArray.getJSONObject(i).getString("1999"));
                Log.d(LOG_TAG, "2000 = " + priceArray.getJSONObject(i).getString("2000"));
                Log.d(LOG_TAG, "2007 = " + priceArray.getJSONObject(i).getString("2007"));
            }

        }catch (JSONException ex){
            Log.e(LOG_TAG, ex.toString());
        }

假设您从PHP api收到了jsonData。我希望这会对你有所帮助:

boolean success = false;
        int temp= 0;
        try {
            JSONObject jsonobject = new JSONObject(jsonData);
            success = jsonobject.getBoolean("success");
            if (success) {
                // Locate the NodeList name
                JSONArray jsonarray = jsonobject.getJSONArray("data");
                for (int i = 0; i < jsonarray.length(); i++) {
                    temp = i+1;
                    jsonobject = jsonarray.getJSONObject(i);
                    String id = jsonobject.getString("FIELD"+temp);
                    String values = jsonobject.getString("value");
                    Log.e(LOG_TAG, "FIElD"+temp+": "+id);
                    Log.e(LOG_TAG, "Value: "+values);
                }
            }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }

答案 1 :(得分:0)

试试这个:

String jsonString3 =
                "[\n" +
                        "    {\n" +
                        "        \"response\": \"\",\n" +
                        "        \"FIELD1\": [\n" +
                        "            {\n" +
                        "                \"value\": \"A\"\n" +
                        "            }\n" +
                        "        ],\n" +
                        "        \"FIELD2\": [\n" +
                        "            {\n" +
                        "                \"value\": \"B\"\n" +
                        "            }\n" +
                        "        ],\n" +
                        "        \"FIELD3\": [\n" +
                        "            {\n" +
                        "                \"value\": \"C\"\n" +
                        "            }\n" +
                        "        ],\n" +
                        "        \"FIELD4\": [\n" +
                        "            {\n" +
                        "                \"value\": \"D\"\n" +
                        "            }\n" +
                        "        ]\n" +
                        "    }\n" +
                        "]";
        try{

            JSONArray data = new JSONArray(jsonString3);
            JSONObject response = data.getJSONObject(0);
            Iterator<?> keys = response.keys();
            while( keys.hasNext() ){
                String key = (String)keys.next();
                if (response.get(key) instanceof JSONArray)
                {
                    JSONArray aArray = (JSONArray) response.getJSONArray(key);
                    for (int i = 0; i < aArray.length(); i++){
                        Log.d(LOG_TAG, "item = " + key);
                        Log.d(LOG_TAG, "it's value = " + aArray.getJSONObject(i).getString("value"));
                    }
                }

            }

        }catch (JSONException ex){
            Log.e(LOG_TAG, ex.toString());
        }

但是,我的JSON是硬编码的。如果你从PHP api收到你的JSON,你应该总结一下这个代码的解决方案(我从我的api得到了我的jsonData):

String jsonData = apiCaller(params);
    boolean success = false;
            int temp= 0;
            try {
                JSONObject jsonobject = new JSONObject(jsonData);
                success = jsonobject.getBoolean("success");
                if (success) {
                    // Locate the NodeList name
                    JSONArray jsonarray = jsonobject.getJSONArray("data");
                    for (int i = 0; i < jsonarray.length(); i++) {
                        temp = i+1;
                        jsonobject = jsonarray.getJSONObject(i);
                        String id = jsonobject.getString("FIELD"+temp);
                        String values = jsonobject.getString("value");
                        Log.e(LOG_TAG, "FIElD"+temp+": "+id);
                        Log.e(LOG_TAG, "Value: "+values);
                    }
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }