【问题标题】:json encode array from php sql server and convert to Android来自php sql server的json编码数组并转换为Android
【发布时间】:2014-11-28 05:15:06
【问题描述】:

您好,我是 android php 客户端服务器的新手。目前,我正在从 php sql server 向 Android 客户端发送来自 sql 行的多个结果的响应。以前,我发送一个简单的字符串并接收如下的android:

$result_data = array( 
'ResultArray' => 'success',
); 

 #Output the JSON data 
 echo json_encode($result_data); 

然后在android中:

// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);

//Retrieve the data from the JSON object
String resultLoging = jsonObject.getString("ResultArray");

现在我想从具有 3 列的数据库接收:id、电话、姓名。我该怎么做?感谢您的帮助

【问题讨论】:

  • 您是否粘贴您的回复。然后我们将为您提供准确的解决方案
  • 以与此处无数类似问题的回答类似的方式
  • 上面的代码只是我简单的字符串编码的例子。我想要具有多个结果的数组

标签: php android sql-server json


【解决方案1】:

在php中使用如下格式

$result = mysql_query("SELECT *FROM tablename") or die(mysql_error());

// check for empty result

if (mysql_num_rows($result) > 0) 

{

    // looping through all results

    // products node

    $response["details"] = array();

    while ($row = mysql_fetch_array($result))

 {

        // temp user array

        $product = array();

        $product["id"] = $row["id"];

        $product["name"] = $row["name"];

array_push($response["details"], $product);

    }

    // success

    $response["success"] = 1;

    // echoing JSON response

    echo json_encode($response);

在安卓中

获取成功值

int success = json.getInt(TAG_SUCCESS);

使用以下格式获取数据

JSONArray spi = json.getJSONArray("details"); 

Use a for loop to get the object values in the array

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

                        JSONObject c = spi.getJSONObject(i);

 id = c.getString("id");

}

【讨论】:

  • id = c.getString("id");这个id是数组还是字符串?
【解决方案2】:

使用 JSONArray 获取多个 json 结果:

JSONArray jsonArray =  jsonObject.getJSONArray("ResultArray");

迭代 JSONArray 并从 JSONObject 获取值:

for (int i=0;i<jsonArray.length();i++){
     JSONObject json = jsonArray.getJSONObject(i);
     String id = json.getString("id");
     String phone = json.getString("phone");
     String name = json.getString("name");
} 

【讨论】:

    【解决方案3】:

    刚刚找到这个,这对我的问题来说是最好的 https://stackoverflow.com/a/3563464/1345454

    $results = array();
    while($row = mysql_fetch_array($sql))
    {
       $results[] = array(
          'title' => base64_decode($row['title']),
          'price' => $row['price'],
          'seller_user' => $row['user']
       );
    }
    $json = json_encode($results);
    

    【讨论】:

      【解决方案4】:

      试试这个

      $result_data = array( 
      'ResultArray' => 'success',
      ); 
      
      echo json_encode(array('result'=>$result_data));
      

      在安卓中

           JSONParser jParser = new JSONParser();
           JSONObject json = jParser.getJSONFromUrl("url of php file");
           JsonArray arry = json.getJSONArray("result");
           JSONObject c = arry .getJSONObject(0);
           String resultarr= c.getString("ResultArray");
      
      
      
      
      
       public class JSONParser {
      
      static InputStream is = null;
      static JSONObject jObj = null;
      static String json = "";
      
      // constructor
      public JSONParser() {
      
      }
      
      // function get json from url
      // by making HTTP POST or GET mehtod
      public JSONObject makeHttpRequest(String url, String method,
              List<NameValuePair> params) {
      
          // Making HTTP request
          try {
      
              // check for request method
              if(method == "POST"){
                  // request method is POST
                  // defaultHttpClient
                  DefaultHttpClient httpClient = new DefaultHttpClient();
                  HttpPost httpPost = new HttpPost(url);
                  httpPost.setEntity(new UrlEncodedFormEntity(params));
      
                  HttpResponse httpResponse = httpClient.execute(httpPost);
                  HttpEntity httpEntity = httpResponse.getEntity();
                  is = httpEntity.getContent();
      
              }else if(method == "GET"){
                  // request method is GET
                  DefaultHttpClient httpClient = new DefaultHttpClient();
                  String paramString = URLEncodedUtils.format(params, "utf-8");
                  url += "?" + paramString;
                  HttpGet httpGet = new HttpGet(url);
      
                  HttpResponse httpResponse = httpClient.execute(httpGet);
                  HttpEntity httpEntity = httpResponse.getEntity();
                  is = httpEntity.getContent();
              }            
      
          } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
          } catch (ClientProtocolException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
      
          try {
              BufferedReader reader = new BufferedReader(new InputStreamReader(
                      is, "iso-8859-1"), 8);
              StringBuilder sb = new StringBuilder();
              String line = null;
              while ((line = reader.readLine()) != null) {
                  sb.append(line + "\n");
              }
              is.close();
              json = sb.toString();
            //  System.out.println(json);
      
          } catch (Exception e) {
              Log.e("Buffer Error", "Error converting result " + e.toString());
          }
      
          // try parse the string to a JSON object
          try {
      
      
      
      
      
              jObj = new JSONObject(json);
          } catch (JSONException e) {
              Log.e("JSON Parser", "Error parsing data " + e.toString());
          }
      
          // return JSON String
          return jObj;
      
         }
        }
      

      【讨论】:

      • jsonparser 来自哪个库?另外,如果它是解析器,为什么它有名为 getJSONFromUrl 的方法?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多