【问题标题】:String Can not converted to JSON Object in Android字符串无法在 Android 中转换为 JSON 对象
【发布时间】:2014-10-22 05:59:36
【问题描述】:

我想从 PHP MySql 填充 Spinner。当我运行应用程序时,它会得到 org.json.JSONException: Value Category_code of type java.lang.String cannot be converted to JSONObject

谁能帮我怎么做。

这是我的代码

    public class Customer_Order_Detail extends Activity
{
    private ArrayList<Category> categoriesList;
    ProgressDialog pDialog;
    Spinner spinnerCategory;

    // Url to get all categories
    private String URL_CATEGORIES = "http://192.168.1.102/client_vendor_mgmt/category_master.php";


    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.customer_order);
        categoriesList = new ArrayList<Category>();
        spinnerCategory = (Spinner)findViewById(R.id.spinnerCategory);
        new GetCategories().execute();
    }

    /**
     * Adding spinner data
     * */
    private void populateSpinner() {
        List<String> lables = new ArrayList<String>();

        for (int i = 0; i < categoriesList.size(); i++)
        {
            lables.add(categoriesList.get(i).getName());
        }

        // Creating adapter for spinner
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, lables);

        // Drop down layout style - list view with radio button
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        spinnerCategory.setAdapter(spinnerAdapter);
    }


    /*
     * Async task to get all  categories
     */

    private class GetCategories extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Customer_Order_Detail.this);
            pDialog.setMessage("Fetching categories..");
            pDialog.setCancelable(false);
            pDialog.show();

        }
        //org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.1.102 refused

        @Override
        protected Void doInBackground(Void... arg0) {
            ServiceHandler jsonParser = new ServiceHandler();
            String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);

            Log.e("Response: ", " > " + json);

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

                    if (jsonObj != null)
                    {
                        JSONArray categories = jsonObj.getJSONArray("category_master");                     

                        for (int i = 0; i < categories.length(); i++)
                        {
                            JSONObject catObj = (JSONObject) categories.get(i);
                            Category cat = new Category(catObj.getInt("cat_id"),catObj.getString("cat_name"));
                            categoriesList.add(cat);
                        }
                    }

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

            } 
            else 
            {
                Log.e("JSON Data", "Didn't receive any data from server!");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);
            if (pDialog.isShowing())
                pDialog.dismiss();

            populateSpinner();
        }

    }


}

这是我的日志猫信息

08-28 16:39:17.854: E/Response:(531): Category_code:--ELEC1Category_nameElectronics
08-28 16:39:17.917: W/System.err(531): org.json.JSONException: Value Category_code of type java.lang.String cannot be converted to JSONObject
08-28 16:39:17.964: W/System.err(531):  at org.json.JSON.typeMismatch(JSON.java:107)
08-28 16:39:17.964: W/System.err(531):  at org.json.JSONObject.<init>(JSONObject.java:158)
08-28 16:39:17.964: W/System.err(531):  at org.json.JSONObject.<init>(JSONObject.java:171)
08-28 16:39:17.964: W/System.err(531):  at com.customer.demo.Customer_Order_Detail$GetCategories.doInBackground(Customer_Order_Detail.java:91)
08-28 16:39:17.974: W/System.err(531):  at com.customer.demo.Customer_Order_Detail$GetCategories.doInBackground(Customer_Order_Detail.java:1)
08-28 16:39:17.984: W/System.err(531):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
08-28 16:39:17.984: W/System.err(531):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
08-28 16:39:17.984: W/System.err(531):  at java.util.concurrent.FutureTask.run(FutureTask.java:138)
08-28 16:39:17.984: W/System.err(531):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
08-28 16:39:17.984: W/System.err(531):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
08-28 16:39:17.994: W/System.err(531):  at java.lang.Thread.run(Thread.java:1019)

这是我的 ServiceHandeller

public class ServiceHandler {

    static InputStream is = null;
    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;

    public ServiceHandler() {

    }

    /*
     * Making service call
     * @url - url to make request
     * @method - http request method
     * */
    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);
    }

    /*
     * Making service call
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     * */
    public String makeServiceCall(String url, int method,
            List<NameValuePair> params) {
        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            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, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            response = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error: " + e.toString());
        }

        return response;

    }
}

【问题讨论】:

  • 你能发布来自服务器的响应吗?
  • @Michael Shrestha - Category_code:--ELEC1Category_nameElectronics 。来自服务器的响应。
  • 发布你的 logcat 的Log.e("Response: ", " &gt; " + json);
  • 请发布 makeServiceCall() ....
  • 检查服务器的响应是否为有效的 JSON。您也可以为此使用在线工具。例如。 jsonlint.com

标签: java android phpmyadmin


【解决方案1】:

这就是你需要的..

JSONObject jsonObject = new JSONObject(jsonString);

为此,您只需将字符串传递给构造函数。

【讨论】:

  • 发布的问题有JSONObject jsonObj = new JSONObject(json); 不一样吗? stacktrace 还指出 org.json.JSONException: Value Category_code of type java.lang.String cannot be convert to JSONObject
  • @Raghunandan :是的,同样的
  • @tazeen 检查makeServiceCall 中的响应。确保您返回了有效的 json。
【解决方案2】:

从您的 logcat 行 Category_code:--ELEC1Category_nameElectronics 它表明您没有得到实际 json 格式的响应。它是简单的字符串格式。

这就是为什么您不能将其转换为 JSONObject 的原因,您在代码中如下所示。

JSONObject jsonObj = new JSONObject(json);

您必须进入String 值。

【讨论】:

  • - 感谢您的回复。对不起,我没听明白。
  • @tazeen 你需要先学习 JSON.. 然后在你的应用程序中使用。
  • @tazeen 服务器的实际响应类似于Category_code:--ELEC1Category_nameElectronics,这是无效的 json 格式。这就是为什么你不能使用 JSONObject 解析它。
  • @GrIsHu :-我已经进入字符串值,如下所示 = String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET); Log.e("响应:", " > " + json); if (json != null) { try { JSONObject jsonObj = new JSONObject(json);
  • @tazeen 请在您的问题中发表您的全部回复。
猜你喜欢
  • 1970-01-01
  • 2015-02-28
  • 1970-01-01
  • 1970-01-01
  • 2013-08-02
  • 1970-01-01
  • 2013-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多