2015-06-03 120 views
0

我試圖開發一個android應用程序,它將連接到外部服務器以獲取數據。我已經用我的.php文件成功讀取了數據,但是我無法在我的應用程序中使用它,因爲它會引發錯誤。解析DB JSON時出錯

<?php 

/** 
* A class file to connect to database 
*/ 


// connect to database 
try { 
$pdo = new PDO('mysql:host=localhost;dbname=myDBname',' user', 'pass'); 
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 
} catch(PDOException $err) { 
die($err->getMessage()); 
} 

$stmt = $pdo->prepare("select * from Test"); 


$result = $stmt->execute(); 
print_r($stmt->fetchAll(PDO::FETCH_ASSOC)); 

?> 

這就是我用來讀取數據的php代碼。這是我在Android Studio中

protected String doInBackground(String... args) { 
      // Building Parameters 
      List params = new ArrayList(); 
      // getting JSON string from URL 

      JSONObject json = jParser.makeHttpRequest(server_php_url, "GET", params); 
      // Check your log cat for JSON reponse 
      Log.d("All Products: ", json.toString()); 

      try { 
       // Checking for SUCCESS TAG 
       int success = json.getInt(TAG_SUCCESS); 

       if (success == 1) { 
        // products found 
        // Getting Array of Products 
        products = json.getJSONArray(TAG_PRODUCTS); 

        // looping through All Products 
        //Log.i("ramiro", "produtos.length" + products.length()); 
        for (int i = 0; i < products.length(); i++) { 
         JSONObject c = products.getJSONObject(i); 

         // Storing each json item in variable 

         String name = c.getString(TAG_NAME); 

         // creating new HashMap 
         HashMap map = new HashMap(); 

         // adding each child node to HashMap key => value 

         map.put(TAG_NAME, name); 

         empresaList.add(map); 
        } 
       } 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
      return null; 
} 

使用代碼這是JSONParser類:

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 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(); 
     } 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; 

    } 
} 

這是JSON的結果: 陣列([0] =>數組([測試] = > Name1)[1] => Array([Name] => Name2))

錯誤信息: E/JSON解析器:解析數據時出錯org.json.JSONException:Value java.lang.String類型的數組無法轉換爲JSONObject

我真的需要幫助。 預先感謝您。

+0

上面的輸出不是json。 JSON是'[{「Test」:「Name1」},{「Name」:「Name2」}]'。試試'json_encode'PHP函數。 – mp911de

+0

那麼,我該怎麼做呢? $ var = json_encode($ result),然後打印$ var? – jk93

+0

我試圖對結果進行編碼,但它沒有寫入「true」。 – jk93

回答

0

在返回變量使用json_decode(),您將獲得以JSON格式輸出DO 作爲

return json_decode(jObj); 
+0

我應該在哪裏使用該代碼? – jk93

0

Retrun JSON對象在後臺方法

protected String doInBackground(String... args) { 
     // Building Parameters 
     List params = new ArrayList(); 
     // getting JSON string from URL 

     JSONObject json = jParser.makeHttpRequest(server_php_url, "GET", params); 
     // Check your log cat for JSON reponse 
     Log.d("All Products: ", json.toString()); 

     try { 
      // Checking for SUCCESS TAG 
      int success = json.getInt(TAG_SUCCESS); 

      if (success == 1) { 
       // products found 
       // Getting Array of Products 
       products = json.getJSONArray(TAG_PRODUCTS); 

       // looping through All Products 
       //Log.i("ramiro", "produtos.length" + products.length()); 
       for (int i = 0; i < products.length(); i++) { 
        JSONObject c = products.getJSONObject(i); 

        // Storing each json item in variable 

        String name = c.getString(TAG_NAME); 

        // creating new HashMap 
        HashMap map = new HashMap(); 

        // adding each child node to HashMap key => value 

        map.put(TAG_NAME, name); 

        empresaList.add(map); 
       } 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return json; 
+0

如果我這樣做,即時返回JSONObject而不是字符串。 – jk93

0

據我所知JSONParser類中引發錯誤的最具體方法如下:

try { 
      jObj = new JSONObject(json); 


     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

I ha ve最終將輸出編碼爲[{「Test」:「Name1」}] ,現在我的錯誤更改爲 解析數據org.json.JSONException時出錯:值[{「Test」:「Name1」}]類型org .json.JSONArray無法轉換爲JSONObject

我會apreciate,如果你可以發佈與mysql相同的.php代碼,因爲我試圖寫它,但它說「mysql被棄用」,我不知道該怎麼做與mysqli。