2012-03-10 114 views
-2

。我是誰開始學習構建一個Android應用程序一個學生......無法將JSONArray轉換爲JSONObject

我遇到對我在這裏的代碼困難....

我讀過許多頁面如何解決這個問題,我的天堂沒有發現它......或者我不明白。 HAHAH

的logcat的總是這樣:

03-10 11:12:43.057: D/dalvikvm(636): GC_EXTERNAL_ALLOC freed 1001 objects/69352 bytes in 99ms 
03-10 11:12:46.458: E/JSON Parser(636): Error parsing data org.json.JSONException: Names must be strings, but [{"pass_mobile":"affanganteng","user_mobile":"affan"},{"pass_mobile":"affandroid1","user_mobile":"affandroid"},{"pass_mobile":"tes","user_mobile":"tes"},{"pass_mobile":"tesdua","user_mobile":"tes2"}] is of type org.json.JSONArray at character 200 of {[{"user_mobile":"affan","pass_mobile":"affanganteng"},{"user_mobile":"affandroid","pass_mobile":"affandroid1"},{"user_mobile":"tes","pass_mobile":"tes"},{"user_mobile":"tes2","pass_mobile":"tesdua"}]} 
03-10 11:35:00.868: D/dalvikvm(644): GC_EXTERNAL_ALLOC freed 1014 objects/69872 bytes in 71ms 
03-10 11:35:03.629: E/JSON Parser(644): Error parsing data org.json.JSONException: Value [{"pass_mobile":"affanganteng","user_mobile":"affan"},{"pass_mobile":"affandroid1","user_mobile":"affandroid"},{"pass_mobile":"tes","user_mobile":"tes"},{"pass_mobile":"tesdua","user_mobile":"tes2"}] of type org.json.JSONArray cannot be converted to JSONObject 
03-10 11:40:58.798: D/dalvikvm(671): GC_EXTERNAL_ALLOC freed 744 objects/59488 bytes in 80ms 
03-10 11:41:03.128: E/JSON Parser(671): Error parsing data org.json.JSONException: Value [{"pass_mobile":"affanganteng","user_mobile":"affan"},{"pass_mobile":"affandroid1","user_mobile":"affandroid"},{"pass_mobile":"tes","user_mobile":"tes"},{"pass_mobile":"tesdua","user_mobile":"tes2"}] of type org.json.JSONArray cannot be converted to JSONObject 

其實我想從我的SQL獲取數據,然後分析它使用JSON來的ListView。 我希望你能幫助我!

這裏是我的主要活動:

package last.project.CuliGUI; 

import java.util.ArrayList; 
import java.util.HashMap; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.ListActivity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.TextView; 

public class AndroidJSONParsingActivity extends ListActivity { 

    // url to make request 
    private static String url = "http://10.0.2.2/culigui/getdatausermobile_2.php"; 

    // JSON Node names 
    //private static final String TAG_LISTUSERMOBILE = "listusermobile"; 
    private static final String TAG_USER_MOBILE = "user_mobile"; 
    private static final String TAG_PASS_MOBILE = "pass_mobile"; 

    // contacts JSONArray 
    JSONArray listusermobile = null; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.menu_view_all); 

     // Hashmap for ListView 
     ArrayList<HashMap<String, String>> userList = new ArrayList<HashMap<String, String>>(); 

     // Creating JSON Parser instance 
     JSONParser jParser = new JSONParser(); 

     // getting JSON string from URL 
     JSONObject json = jParser.getJSONFromUrl(url); 

     try { 
      // Getting Array of Contacts 
      //listusermobile = json.getJSONArray(TAG_LISTUSERMOBILE); 
      listusermobile = json.getJSONArray(null); 

      // looping through All Contacts 
      for(int i = 0; i < listusermobile.length(); i++){ 
       JSONObject c = listusermobile.getJSONObject(i); 

       // Storing each json item in variable 
       String username = c.getString(TAG_USER_MOBILE); 
       String password = c.getString(TAG_PASS_MOBILE); 

       // creating new HashMap 
       HashMap<String, String> map = new HashMap<String, String>(); 

       // adding each child node to HashMap key => value 
       map.put(TAG_USER_MOBILE, username); 
       map.put(TAG_PASS_MOBILE, password); 
       // adding HashList to ArrayList 
       userList.add(map); 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 


     /** 
     * Updating parsed JSON data into ListView 
     * */ 
     ListAdapter adapter = new SimpleAdapter(this, userList, 
       R.layout.menu_view_all, 
       new String[] { TAG_USER_MOBILE, TAG_PASS_MOBILE}, new int[] { 
         R.id.name, R.id.pass }); 

     setListAdapter(adapter); 

     // selecting single ListView item 
     ListView lv = getListView(); 

     // Launching new screen on Selecting Single ListItem 
     lv.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> parent, View view, 
        int position, long id) { 
       // getting values from selected ListItem 
       String name = ((TextView) view.findViewById(R.id.name)).getText().toString(); 
       String pass = ((TextView) view.findViewById(R.id.pass)).getText().toString(); 

       // Starting new intent 
       Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class); 
       in.putExtra(TAG_USER_MOBILE, name); 
       in.putExtra(TAG_PASS_MOBILE, pass); 
       startActivity(in); 

      } 
     }); 



    } 

} 

,在這裏我JSONParser類:

package last.project.CuliGUI; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 

public class JSONParser { 

    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 

    // constructor 
    public JSONParser() { 

    } 

    public JSONObject getJSONFromUrl(String url) { 

     // Making HTTP request 
     try { 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      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; 

    } 
} 

和這裏的PHP:

<?php 

    $link = mysql_connect('localhost', 'root', '') or die('Cannot connect to the DB'); 
    mysql_select_db('culigui', $link) or die('Cannot select the DB'); 



    $result = sql2json("SELECT * FROM data_mobile"); 

    echo $result; 

    //Function will take an SQL query as an argument and format the resulting data as a 
// json(JavaScript Object Notation) string and return it. 
function sql2json($query) { 
    $data_sql = mysql_query($query) or die("'';//" . mysql_error());// If an error has occurred, 
      // make the error a js comment so that a javascript error will NOT be invoked 
    $json_str = ""; //Init the JSON string. 

    if($total = mysql_num_rows($data_sql)) { //See if there is anything in the query 
     $json_str .= "[\n"; 

     $row_count = 0;  
     while($data = mysql_fetch_assoc($data_sql)) { 
      if(count($data) > 1) $json_str .= "{\n"; 

      $count = 0; 
      foreach($data as $key => $value) { 
       //If it is an associative array we want it in the format of "key":"value" 
       if(count($data) > 1) $json_str .= "\"$key\":\"$value\""; 
       else $json_str .= "\"$value\""; 

       //Make sure that the last item don't have a ',' (comma) 
       $count++; 
       if($count < count($data)) $json_str .= ",\n"; 
      } 
      $row_count++; 
      if(count($data) > 1) $json_str .= "}\n"; 

      //Make sure that the last item don't have a ',' (comma) 
      if($row_count < $total) $json_str .= ",\n"; 
     } 

     $json_str .= "]\n"; 
    } 

    //Replace the '\n's - make it faster - but at the price of bad redability. 
    $json_str = str_replace("\n","",$json_str); //Comment this out when you are debugging the script 

    //Finally, output the data 
    return $json_str; 
} 


?> 

回答

0

的所有第一,以下是NOT有效的JSON對象:

{ 
    [ 
     { 
      "user_mobile": "affan", 
      "pass_mobile": "affanganteng" 
     }, 
     { 
      "user_mobile": "affandroid", 
      "pass_mobile": "affandroid1" 
     }, 
     { 
      "user_mobile": "tes", 
      "pass_mobile": "tes" 
     }, 
     { 
      "user_mobile": "tes2", 
      "pass_mobile": "tesdua" 
     } 
    ] 
} 

在Java代碼中,你遍歷JSON對象,並獲得小組JSON對象..

JSONObject c = listusermobile.getJSONObject(i); 

但JSON對象裏面,你都拿着JSON Array ([]),不是JSON Object ({}) ..但你想類型轉換JSON ArrayJSON Object.。那是什麼導致了錯誤...

注意:您ç始終驗證「一個有效的JSONObject」和「有效JSONArray」在JSONLint.com

+0

感謝@RamandeepSingh指正我的JSON對象... 我正確的,這樣的: [ { 「user_mobile」 : 「阿凡」, 「pass_mobile」: 「affanganteng」 }, { 「user_mobile」: 「affandroid」, 「pass_mobile」: 「affandroid1」 }, { 「user_mobile」: 「TES」, 「pass_mobile」:「tes」 }, { 「user_mobile」: 「TES2」, 「pass_mobile」: 「tesdua」 } ] ,這是一個有效的JSON。 其實我不明白「嘗試TYPECAST JSON數組到JSON對象」 你能解釋我更多嗎? 謝謝anwy。 – 2012-03-10 15:20:28

+0

正如我從你的PHP代碼可以看到,你正在發送這種類型的JSON字符串:** [{},{},....] ** ....和你的函數在java ** JSONObject json = jParser.getJSONFromUrl(url); **實際上是試圖獲取一個** JSON對象**,但它得到一個** JSONArray ** .. !! – 2012-03-10 15:55:40

相關問題