简体   繁体   English

错误JSONArray无法转换为JSONObject

[英]Error JSONArray cannot be converted to JSONObject

I created an application to parse Json data from server to my app. 我创建了一个应用程序以将Json数据从服务器解析到我的应用程序。 But now When I run the project I get a JSONArray cannot be converted to JSONObject exception.I get all the server data in my LogCat view but not in the application. 但是现在当我运行项目时,我无法将JSONArray转换为JSONObject异常。我在LogCat视图中获得了所有服务器数据,但在应用程序中却没有。 I tried with different methods but had no luck. 我尝试了不同的方法,但是没有运气。 Thank you. 谢谢。

// This is my main code //这是我的主要代码

    public class jsonExample2 extends Activity{
            // This is the url that i try to get data
        private static String url = "http://api.worldbank.org/countries/ir?format=json";
        private static final String PAGE = "page";
        private static final String VALUE = "value";
        private static final String NAME = "name";
        private static final String GEO = "region";

        JSONArray page = null;
            @Override
            protected void onCreate(Bundle savedInstanceState) {

                super.onCreate(savedInstanceState);
                setContentView(R.layout.activitybw);
                new GetJSONTask().execute(url);

            }

            class GetJSONTask extends AsyncTask<String, Void, JSONObject> {

                protected JSONObject doInBackground(String... urls) {
                    try {
                        JSONParser jParser = new JSONParser();
                        return jParser.getJSONFromUrl(urls[0]);
                    } catch (Exception e) {
                        return null;
                    }
                }

                protected void onPostExecute(JSONObject json) {
                    // do all the parsing here:
                    try {

                        page = json.getJSONArray(PAGE);
                        JSONObject c = page.getJSONObject(0);


                        String value = c.getString(VALUE);
                        String name = c.getString(NAME);
                        String geo = c.getString(GEO);

                        final TextView id1 = (TextView) findViewById(R.id.id);
                        final TextView name1 = (TextView) findViewById(R.id.name);
                        final TextView geo1 = (TextView) findViewById(R.id.geo);

                        id1.setText(value);
                        name1.setText(name);
                        geo1.setText(geo);
                    }
                    catch (JSONException e)
                    {
                        e.printStackTrace();
                    }
                } 
           }        
    }

// JSONParser class // JSONParser类

    public class JSONParser {

        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";

        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 {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
            return jObj;
        }

    }

// This is my logCat view //这是我的logCat视图

    03-19 09:11:52.776: D/dalvikvm(1376): GC_CONCURRENT freed 129K, 10% free 2629K/2904K, paused 75ms+101ms, total 286ms
    03-19 09:11:52.846: E/JSON Parser(1376): Error parsing data org.json.JSONException: Value [{"total":1,"page":1,"per_page":"50","pages":1},[{"region":{"value":"Middle East & North Africa (all income levels)","id":"MEA"},"id":"IRN","incomeLevel":{"value":"Upper middle income","id":"UMC"},"name":"Iran, Islamic Rep.","iso2Code":"IR","lendingType":{"value":"IBRD","id":"IBD"},"longitude":"51.4447","latitude":"35.6878","capitalCity":"Tehran","adminregion":{"value":"Middle East & North Africa (developing only)","id":"MNA"}}]] of type org.json.JSONArray cannot be converted to JSONObject
    03-19 09:11:52.846: D/AndroidRuntime(1376): Shutting down VM
    03-19 09:11:52.855: W/dalvikvm(1376): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
    03-19 09:11:52.876: E/AndroidRuntime(1376): FATAL EXCEPTION: main
    03-19 09:11:52.876: E/AndroidRuntime(1376): java.lang.NullPointerException
    03-19 09:11:52.876: E/AndroidRuntime(1376):     at com.example.mediaplayerapp.jsonExample2$GetJSONTask.onPostExecute(jsonExample2.java:79)
  try {
     jObj = new JSONObject(json);
  } catch (JSONException e) {
     Log.e("JSON Parser", "Error parsing data " + e.toString());
  }

this is wrong. 这是错误的。 You are getting a JSONArray but you are converting it to JSONObject . 您正在获取JSONArray但正在将其转换为JSONObject Change it in 改变它

try {
     if (json != null)
       return new JSONArray(json);
  } catch (JSONException e) {
     Log.e("JSON Parser", "Error parsing data " + e.toString());
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM