获取无法将jsonarray转换为json对象

时间:2013-02-20 06:01:05

标签: android json exception

您好我正在开发一个使用mysql数据库的应用程序,但是当我尝试获取值并显示它时,我收到以下错误。

02-20 05:48:33.021: W/System.err(1723): org.json.JSONException: Value [{"3":"images\/BigBazaar.png","2":"Jayanagar 4th Block","outlet_name":"Big Bazaar","1":"Big Bazaar","0":"1","outlet_image":"images\/BigBazaar.png","outlet_location":"Jayanagar 4th Block","outlet_id":"1"}] of type org.json.JSONArray cannot be converted to JSONObject

我也能在日志中看到输出,即

02-20 05:48:33.380: I/TAG(1723): [{"0":"1","outlet_id":"1","1":"Big Bazaar","outlet_name":"Big Bazaar","2":"Jayanagar 4th Block","outlet_location":"Jayanagar 4th Block","3":"images\/BigBazaar.png","outlet_image":"images\/BigBazaar.png"}]

这是我的代码。

public class StoreActivity extends Activity {
    private String mBaseUrl="http://192.168.1.5/Flutura/PHP/";  
    private String mDataUrl=mBaseUrl+"Core/Data/android.data3.php";
    private String mAssetsUrl=mBaseUrl+"Assets/";
    private String mRequest="outlet";
    private String mOutletID="0";

    private String mRecommendedProducts="";
    private String mOutletDetails="";
    private SharedPreferences myPrefs ;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.store);      
        myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);             
        mOutletID = myPrefs.getString("outlet_id", "0");
        mOutletDetails = myPrefs.getString("outlet_details","{}");
        Log.v("outlet_details",myPrefs.getString("outlet_details","{}"));
        if(mOutletDetails != "{}"){
            setOutletData(mOutletDetails);
        }
        else{
            executeAjaxRequest();
        }
    }    

    private void executeAjaxRequest(){

       String url = mDataUrl+"?request="+mRequest+"&outlet_id="+mOutletID;
       Log.v("url",url);

       AsyncHttpClient httpclient = new AsyncHttpClient();
       httpclient.get(url, new AsyncHttpResponseHandler() {
         @Override
         public void onSuccess(String response) {
            setOutletData(response);
            Log.i("TAG",response);
         }
       });
     }
    private void setOutletData(String response){
        try{            


        JSONObject store = new JSONObject(response); 

        ImageView store_avatar = (ImageView) findViewById(R.id.store_avatar);  
        TextView store_id      = (TextView)  findViewById(R.id.store_id);
        TextView store_name    = (TextView)  findViewById(R.id.store_name);
        TextView store_loc     = (TextView)  findViewById(R.id.store_location); 

        if(store_avatar != null){
        /*  
          int resid;
          resid = getApplicationContext().getResources().getIdentifier(store.getString("outlet_image").replaceAll(".png",""), "drawable", "org.flutura.recommendation");                  
          store_avatar.setImageResource(resid);*/
            ImageDownloader imdload = new ImageDownloader();
            imdload.setMode(ImageDownloader.Mode.CORRECT);
            imdload.download(mAssetsUrl+store.getString("outlet_image"),store_avatar    );  

          mOutletDetails = store.toString();
          mRecommendedProducts = store.getString("recommended_products");
          store_avatar.setClickable(true);
          store_avatar.setOnClickListener(new View.OnClickListener() {

           @Override
           public void onClick(View v) {
             // TODO Auto-generated method stub
             Intent myIntent = new Intent(StoreActivity.this,StoreMapActivity.class);
             SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
             SharedPreferences.Editor prefsEditor = myPrefs.edit();

             prefsEditor.putString("outlet_details", mOutletDetails);
             prefsEditor.commit();
             startActivity(myIntent);
           }
         });
        }

        mOutletID = store.getString("outlet_id");

        if(store_id != null){
          store_id.setText(mOutletID);
        }

        if(store_name != null){
          store_name.setText(store.getString("outlet_desc"));
        }

        if(store_loc != null){
          store_loc.setText(store.getString("outlet_loc"));
        }

        Button recommended_products_button = (Button) findViewById(R.id.recommended_products_button);
        recommended_products_button.setOnClickListener(new View.OnClickListener(){

           @Override
           public void onClick(View v){

              // Load the recommended products screen
              Intent myIntent = new Intent(StoreActivity.this,RecommendedProductsListActivity.class);
               SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
               SharedPreferences.Editor prefsEditor = myPrefs.edit();               

               prefsEditor.putString("outlet_id",mOutletID);
               prefsEditor.putString("recommended_products", mRecommendedProducts);
               prefsEditor.commit();
               startActivity(myIntent);                    
           }

        });

        Button category_wise_sales_button = (Button) findViewById(R.id.category_wise_sales_button);
        category_wise_sales_button.setOnClickListener(new View.OnClickListener(){

           @Override
           public void onClick(View v){

              // Load the recommended products screen
              Intent myIntent = new Intent(StoreActivity.this,CategoryWiseSalesActivity.class);
               SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
               SharedPreferences.Editor prefsEditor = myPrefs.edit();               

               prefsEditor.putString("outlet_id",mOutletID);
               prefsEditor.commit();
               startActivity(myIntent);                    
           }

        });
        }
        catch(JSONException e){
            e.printStackTrace();
        }
        catch(NullPointerException e){
            e.printStackTrace();
        }
    }

}

这是我的PHP代码。

<?php
error_reporting(0);

//$url = $_GET['url'];
//$mR = $_GET['mRequest'];
$mOid = $_GET['mOutletId'];
//$mloc = $_GET['mLocation'];
//connect to the db
$user = "root";
$pswd = "";
$db = "recommendations_db";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);
//if($mR == 'outlets' && $mloc = 'all'){
$query = "SELECT outlet_id,outlet_name,outlet_location,outlet_image FROM outlets WHERE outlet_id = '$mOid'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());

//while($row = mysql_fetch_array($result))
  //{
  $output[] = mysql_fetch_array($result); 
  //}
print( json_encode($output));
?>

任何人都可以告诉我出了什么问题,因为我的时间紧迫,需要今天完成。

搜索按钮代码。

search_button.setClickable(true);
      search_button.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        // TODO Auto-generated method stub
        String outlet_no = outlet_id.getText().toString();
        if(!outlet_no.isEmpty()){
        @SuppressWarnings("deprecation")
        SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
        SharedPreferences.Editor prefsEditor = myPrefs.edit();

        prefsEditor.putString("outlet_id", outlet_no);
        prefsEditor.commit();

        Intent myIntent = new Intent(HomeActivity.this, StoreActivity.class);       
        startActivity(myIntent);
        HomeActivity.this.startActivity(myIntent);
        }
        else{
          Toast.makeText(getApplicationContext(), "Please enter an outlet id", Toast.LENGTH_SHORT);
        }  
      }
    });

1 个答案:

答案 0 :(得分:3)

  

获取无法将jsonarray转换为json对象

因为你从服务器获取JSONArray而不是JSONObject所以只需通过将String转换为jsonArray来改变你的代码:

JSONArray jsonArr = new JSONArray(response);  //<<< convert to jsonarray

// extract jsonObejct from JsonArray
JSONObject store = jsonArr.getJSONObject(0); 

而不是

JSONObject store = new JSONObject(response); 
相关问题