2012-03-10 113 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

相关问题