Error:Json parsing error: Value connection of type java.lang.String cannot be converted to JSONObject

Error:Json parsing error: Value connection of type java.lang.String cannot be converted to JSONObject

我没有在我的 listactivity.i 中得到 Json 响应尝试了所有但它没有显示结果..在 logcat 我得到了成功的连接和数据我也可以看到..但在我的列表视图中它说这个例外。 这是我的代码

public class TypeMenu extends AppCompatActivity {

private String TAG = TypeMenu.class.getSimpleName();

private ProgressDialog pDialog;
private ListView lv;

// URL to get contacts JSON
private static String url = "http://cloud.granddubai.com/brtemp/index.php";

ArrayList<HashMap<String, String>> contactList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_type_menu);

    contactList = new ArrayList<>();

    lv = (ListView) findViewById(R.id.list);

    new GetContacts().execute();
    }

  /**
    * Async task class to get json by making HTTP call
   */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(TypeMenu.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();
        Toast.makeText(getApplicationContext(),
                "Toast",
                Toast.LENGTH_LONG)
                .show();

      }

      @Override
      protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
          String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);





        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray contacts = jsonObj.getJSONArray("menu_type");

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

                    String id = c.getString("id");
                    String type = c.getString("type");
                    //String email = c.getString("email");
                  // String address = c.getString("address");
                  // String gender = c.getString("gender");

                   // Phone node is JSON Object
                   //JSONObject phone = c.getJSONObject("phone");
                   //String mobile = phone.getString("mobile");
                //   String home = phone.getString("home");
                 //  String office = phone.getString("office");

                    // tmp hash map for single contact
                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    contact.put("id", id);
                    contact.put("name", type);
                   //contact.put("email", email);
                    //contact.put("mobile", mobile);

                    // adding contact to contact list
                    contactList.add(contact);


                }
                } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
           } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for    possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
                 });

             }

        return null;
        }

       @Override
        protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                TypeMenu.this, contactList,
                R.layout.list_item, new String[]{"id", "type"}, new int[]  {R.id.id,
                R.id.type});

        lv.setAdapter(adapter);
        }

   }
   }

这是我的logcat消息

12-15 14:25:26.092 549-962/com.example.zass.broccoli E/TypeMenu: Response from url: connection successful[{"id":"1","type":"pizza"}, {"id":"8","type":"Special Offer"},{"id":"2","type":"Pasta"},{"id":"7","type":"Soup"},{"id":"6","type":"Beverages"},{"id":"5","type":"Breakfast"},{"id":"3","type":"Lasagna"},{"id":"4","type":"Salad"}] 12-15 14:25:26.092 549-962/com.example.zass.broccoli E/TypeMenu: Json parsing error: Value connection of type java.lang.String cannot be converted to JSONObject

this is the output from url which i wanted in my listview
    [{"id":"1","type":"pizza"},{"id":"8","type":"Special Offer"},       {"id":"6","type":"Beverages"},{"id":"5","type":"Breakfast"},  {"id":"3","type":"Lasagna"},{"id":"4","type":"Salad"}]



  here is my json file which works fine on server
    <?php 
    include ('config.php');
   $id = $_GET['id'];
   $sql = mysqli_query($conn,"SELECT * FROM menu_type ");
    $i=0;
    while($result = mysqli_fetch_array($sql))
    {
      $arr[$i]['id']= $result['id'];
       $arr[$i]['type']= $result['type'];
      }
       echo json_encode($arr);


       ?>

这是我的 list_item.xml

 <LinearLayout    

     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >



    <TextView
        android:id="@+id/id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/type"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

     </LinearLayout>

编辑了你的一些代码试试下面的代码。

   try {
        JSONArray jsonArry = new JSONArray(jsonStr);


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

            String id = c.getString("id");
            String type = c.getString("type");

            // tmp hash map for single contact
            HashMap<String, String> contact = new HashMap<>();

            // adding each child node to HashMap key => value
            contact.put("id", id);
            contact.put("name", type);

            // adding contact to contact list
            contactList.add(contact);


        }
    } catch (final JSONException e) {
        Log.e(TAG, "Json parsing error: " + e.getMessage());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(),
                        "Json parsing error: " + e.getMessage(),
                        Toast.LENGTH_LONG)
                        .show();
            }
        });

    }

应用此代码

JSONArray jsonArry = new JSONArray(jsonStr);
for (int i = 0; i < jsonArry.length(); i++) {
   JSONObject c = jsonArry.getJSONObject(i);
   String id = c.getString("id");
   String type = c.getString("type");
   HashMap<String, String> contact = new HashMap<>();

   contact.put("id", id);
   contact.put("name", type);
   contactList.add(contact);
}

更改以下代码

ListAdapter adapter = new SimpleAdapter(
            TypeMenu.this, contactList,
            R.layout.list_item, new String[]{"id", "type"}, new int[]  {R.id.id,
            R.id.type});  

ListAdapter adapter = new SimpleAdapter(
            TypeMenu.this, contactList,
            R.layout.list_item, new String[]{"id", "name"}, new int[]  {R.id.id,
            R.id.type});

而且我可以再给出一个简单可行的解决方案,

将您的服务器文件更改为如下所示,

<?php 
    include ('config.php');
    $id = $_GET['id'];
    $sql = mysqli_query($conn,"SELECT * FROM menu_type ");
    $response['details'] = array();
    $i=0;
    while($result = mysqli_fetch_array($sql))
    {
        $arr['id']= $result['id'];
        $arr['type']= $result['type'];
        array_push($response['details'],$arr);
    }
    echo json_encode($response);
?>

你的 Java 代码会像,

JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray detailArray = jsonObj.optJSONArray("details");
for (int i = 0; i < detailArray.length(); i++) {
    JSONObject c = detailArray.getJSONObject(i);
    String id = c.getString("id");
    String type = c.getString("type");
    HashMap<String, String> contact = new HashMap<>();

    contact.put("id", id);
    contact.put("name", type);
    contactList.add(contact);
}