org.json.JSONException:org.json.JSONArray类型的值[....]无法转换为JSONObject

时间:2014-10-25 12:46:32

标签: android jsonexception

坚持这个错误.. :( 这是我的代码.. json异常无法转换为jsonobject ..

这是我的Furniture.java文件。这是首先执行的主文件 我想将布局显示为列表视图,其中显示了徽标,家具名称及其价格。

public class Furniture extends Activity
{
TextView login;
ListView list;
Button b,search;
String s,s1="error";
int value;



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

    String strUrl = "http://realroom.byethost24.com/realroom/furniture.php"

    Log.d("c1 :", s1);
    DownloadTask downloadTask = new DownloadTask();
    downloadTask.execute(strUrl);
    list = (ListView) findViewById(R.id.flist);     
 }

 public boolean onCreateOptionsMenu(Menu menu) 
 {
    // TODO Auto-generated method stub
    super.onCreateOptionsMenu(menu);
    MenuInflater blowup = getMenuInflater();
    blowup.inflate(R.menu.menu, menu);
    return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) 
 {
    // TODO Auto-generated method stub
    Intent i;
    switch(item.getItemId())
    {
        case R.id.checkout:
            i = new Intent(Furniture.this, Payment.class);
            startActivity(i);
            break;

        case R.id.aboutUs:
           i = new Intent(Furniture.this,AboutUs.class);
           startActivity(i);
           break;

        case R.id.profile:
           i = new Intent(Furniture.this,Profile.class);
           startActivity(i);
           break;

        case R.id.help:
           i = new Intent(Furniture.this,Help.class);
           startActivity(i);
           break;

    }
    return false;
 }


 private String downloadUrl(String strUrl) throws IOException
 {
    String data = "";
    InputStream istream = null;
    try
    {
        Log.d("c2",s1);
        URL url = new URL(strUrl);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();
        istream = urlConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(istream));
        StringBuffer sb = new StringBuffer();
        String line = "";
        while((line=br.readLine())!=null)
        {
            sb.append(line);
        }
        data = sb.toString();
        br.close();
    }
    catch(Exception e)
    {
        Log.e("c3",s1);
        Log.d("Exception while downloading url", e.toString());
    }
    finally
    {
        istream.close();
    }
    return data;
 }

/** AsyncTask to download json data */
 private class DownloadTask extends AsyncTask<String, Integer, String>
 {
    String data = null;
    @Override
    protected String doInBackground(String... url) 
    {
        try
        {
            data = downloadUrl(url[0]);
            Log.d("c26",s1);
            System.out.print(data);
        }
        catch(Exception e)
        {
            Log.d("Background Task",e.toString());
            Log.e("c6",s1);
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) 
    {

        // The parsing of the xml data is done in a non-ui thread
        ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();

        // Start parsing xml data
        listViewLoaderTask.execute(result);
    }
}

/** AsyncTask to parse json data and load ListView */
 private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>
 {

    JSONObject jObject;
    // Doing the parsing of xml data in a non-ui thread
    @Override
    protected SimpleAdapter doInBackground(String... strJson) 
    {
        try
        {
            Log.d("c4",s1);
            jObject = new JSONObject(strJson[0]);
            Log.d("c44",s1);
            FurnitureJsonParser furnitureJsonParser = new FurnitureJsonParser();
            Log.d("c84",s1);
            furnitureJsonParser.parse(jObject);
            Log.d("c94",s1);
        }
        catch(Exception e)
        {
            Log.d("JSON Exception1",e.toString());
            Log.e("c5",s1);
        }

        // Instantiating json parser class
        FurnitureJsonParser furnitureJsonParser = new FurnitureJsonParser();

        // A list object to store the parsed countries list
        List<HashMap<String, Object>> furnitures = null;

        try
        {
            // Getting the parsed data as a List construct
            furnitures = furnitureJsonParser.parse(jObject);
        }
        catch(Exception e)
        {
            Log.d("Exception",e.toString());
            Log.e("c7",s1);
        }

        // Keys used in Hashmap
        String[] from = { "furniture","flag","details"};

        // Ids of views in listview_layout
        int[] to = { R.id.tv_fur,R.id.iv_icon,R.id.tv_fur_details};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), furnitures, R.layout.f_item, from, to);

        return adapter;
    }

    /** Invoked by the Android on "doInBackground" is executed */
    @Override
    protected void onPostExecute(SimpleAdapter adapter) {

        // Setting adapter for the listview
        list.setAdapter(adapter);
        Log.d("c8",s);
        for(int i=0;i<adapter.getCount();i++)
        {
            HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
            String imgUrl = (String) hm.get("flag_path");
            ImageLoaderTask imageLoaderTask = new ImageLoaderTask();

            HashMap<String, Object> hmDownload = new HashMap<String, Object>();
            hm.put("flag_path",imgUrl);
            hm.put("position", i);
            Log.d("c9",s1);
            // Starting ImageLoaderTask to download and populate image in the listview
            imageLoaderTask.execute(hm);
        }
    }
}


/** AsyncTask to download and load an image in ListView */
 private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{

    @Override
    protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {

        InputStream iStream=null;
        Log.d("c10",s1);
        String imgUrl = (String) hm[0].get("flag_path");
        int position = (Integer) hm[0].get("position");
        URL url;
        Log.d("c11",s1);
        try 
        {
            url = new URL(imgUrl);

            // Creating an http connection to communicate with url
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            // Getting Caching directory
            File cacheDirectory = getBaseContext().getCacheDir();

            Log.d("c12",s1);
            // Temporary file to store the downloaded image
            File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".jpeg");

            Log.d("c13",s1);
            // The FileOutputStream to the temporary file
            FileOutputStream fOutStream = new FileOutputStream(tmpFile);

            // Creating a bitmap from the downloaded inputstream
            Bitmap b = BitmapFactory.decodeStream(iStream);

            // Writing the bitmap to the temporary file as png file
            b.compress(Bitmap.CompressFormat.JPEG,100, fOutStream);

            // Flush the FileOutputStream
            fOutStream.flush();

           //Close the FileOutputStream
           fOutStream.close();

            // Create a hashmap object to store image path and its position in the listview
            HashMap<String, Object> hmBitmap = new HashMap<String, Object>();

            // Storing the path to the temporary image file
            hmBitmap.put("flag",tmpFile.getPath());

            // Storing the position of the image in the listview
            hmBitmap.put("position",position);

            // Returning the HashMap object containing the image path and position
            return hmBitmap;

        }
        catch (Exception e) 
        {
            e.printStackTrace();
            Log.e("c14",s1);
        }
        return null;
    }

    @Override
    protected void onPostExecute(HashMap<String, Object> result) 
    {
        Log.d("c15",s1);
        // Getting the path to the downloaded image
        String path = (String) result.get("flag");

        // Getting the position of the downloaded image
        int position = (Integer) result.get("position");

        // Getting adapter of the listview
        SimpleAdapter adapter = (SimpleAdapter ) list.getAdapter();

        // Getting the hashmap object at the specified position of the listview
        HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);

        // Overwriting the existing path in the adapter
        hm.put("flag",path);

        // Noticing listview about the dataset changes
        adapter.notifyDataSetChanged();
    }
}

}

FurnitureJsonParser.java文件

此文件用于通过JSON解析数据

class FurnitureJsonParser 
{
String s="error";
public List<HashMap<String,Object>> parse(JSONObject jObject)
{
    JSONArray jFurnitures = null;
    try
    {
        jFurnitures = jObject.getJSONArray("furnitures");
    }
    catch(JSONException e)
    {
        e.printStackTrace();
    }
    return getFurnitures(jFurnitures);
}

private List<HashMap<String, Object>> getFurnitures(JSONArray jFurnitures)
{
    int furnitureCount = jFurnitures.length();
    List<HashMap<String, Object>> furnitureList = new ArrayList<HashMap<String,Object>>();
    HashMap<String, Object> furniture = null;

    for(int i=0; i<furnitureCount;i++)
    {
        try
        {
            furniture = getFurniture((JSONObject)jFurnitures.get(i));
            furnitureList.add(furniture);
            Log.d("c18",s);
        }
        catch (JSONException e) 
        {
            e.printStackTrace();
            Log.e("c19",s);
        }
    }

    return furnitureList;
}    

private HashMap<String, Object> getFurniture(JSONObject jFurniture)
{
    HashMap<String, Object> furniture = new HashMap<String, Object>();
    String furnitureName = "";
    String flag="";
    String language = "";
    try
    {
        furnitureName = jFurniture.getString("furniture_name");
        flag = jFurniture.getString("furniture_image");
        language = jFurniture.getString("furniture_cost");
        String details =        "Language : " + language + "\n"
        furniture.put("furniture", furnitureName);
        furniture.put("flag", R.drawable.blank);
        furniture.put("flag_path", flag);
        furniture.put("details", details);
        Log.d("c20",s);

    } catch (JSONException e) 
    {
        e.printStackTrace();
        Log.e("c21",s);
    }
    return furniture;
}
}

furniture.php文件

从数据库中获取信息并发送到android

的php文件
<?php
include('config.php');
date_default_timezone_set("Asia/Calcutta");

$result1 = mysqli_query($con,"SELECT furniture_name, furniture_image, furniture_cost FROM tbl_furniture");

while($row=mysqli_fetch_array($result1))
{
    //$row['store_name'];
    //echo"<br>";
    $back_android[]=$row;
}

print(json_encode($back_android));

?>

furniture.xml文件

家具档案的布局

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
tools:context=".MainActivity"
>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    android:background="@drawable/bg"
>


<Button
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:id="@+id/search"
     android:layout_gravity="center"
     android:text="Search for Furniture"
     android:textSize="10dp"
     android:textColor="#AAAAAA"
 />

<TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:id="@+id/sf"
     android:layout_gravity="center"
     android:text="Select Furniture"
     android:textSize="20dp"
     android:textColor="#FFFFFF"
 />

    <ListView
        android:id="@+id/flist"
        android:layout_width="fill_parent"
        android:layout_height="402dp"
        android:layout_marginTop="10dp"
        android:layout_weight="0.18" >
    </ListView>



</LinearLayout>
</ScrollView>

f_item.xml文件

在furniture.xml文件中列表视图的布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:id="@+id/tv_fur"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:textSize="20dp"
    android:textStyle="bold" />

<ImageView
    android:id="@+id/iv_icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/tv_fur"
    android:layout_centerVertical="true"
    android:padding="5dp"
    android:contentDescription="@string/str_iv_flag" />

<TextView
    android:id="@+id/tv_fur_details"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@id/iv_icon"
    android:layout_below="@id/tv_fur"  />

</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

以下代码将根据此JSON

返回家具列表
private List<Furniture> getThemFurnitures(String json){

    List<Furniture> furnitures = new ArrayList<Furniture>();

    try {
        JSONObject jsonRoot = new JSONObject(json);
        JSONArray jsonArray = jsonRoot.getJSONArray("furnitures");

        for(int i = 0; i < jsonArray.length(); i++){
            JSONObject furnitureObject = jsonArray.getJSONObject(i);
            String storeID = furnitureObject.getString("store_id");
            String name = furnitureObject.getString("furniture_name");
            String cost = furnitureObject.getString("furniture_cost");
            String image = furnitureObject.getString("furniture_image");

            furnitures.add(new Furniture(storeID, name, cost, image));
        }

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

    return furnitures;
}