类型org.json.jsonobject无法转换为jsonarray

时间:2014-10-15 06:49:23

标签: android json listview

我的应用程序有问题,我的logcat显示tt类型org.json.jsonobject无法转换为jsonarray。我不知道如何解决这个问题。这是什么意思?如何更改我的代码

这里是logcat信息:

10-15 06:33:05.394: E/JSON Parser(1322): Error parsing data org.json.JSONException: Value {"table2":[{"status":"queueing","phonenumber":"123","remarks":"w","peoplenumber":"5"},{"status":"","phonenumber":"345","remarks":"ss","peoplenumber":"3"},{"status":"","phonenumber":"555","remarks":"f","peoplenumber":"2"},{"status":"","phonenumber":"1345","remarks":"","peoplenumber":"5"}]} of type org.json.JSONObject cannot be converted to JSONArray
10-15 06:33:05.394: W/dalvikvm(1322): threadid=11: thread exiting with uncaught exception (group=0xa4d80b20)
10-15 06:33:05.394: E/AndroidRuntime(1322): FATAL EXCEPTION: AsyncTask #1
10-15 06:33:05.394: E/AndroidRuntime(1322): Process: com.zanqi.datatolistview, PID: 1322
10-15 06:33:05.394: E/AndroidRuntime(1322): java.lang.RuntimeException: An error occured while executing doInBackground()
10-15 06:33:05.394: E/AndroidRuntime(1322):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
10-15 06:33:05.394: E/AndroidRuntime(1322):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
10-15 06:33:05.394: E/AndroidRuntime(1322):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
10-15 06:33:05.394: E/AndroidRuntime(1322):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
10-15 06:33:05.394: E/AndroidRuntime(1322):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
10-15 06:33:05.394: E/AndroidRuntime(1322):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
10-15 06:33:05.394: E/AndroidRuntime(1322):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
10-15 06:33:05.394: E/AndroidRuntime(1322):     at java.lang.Thread.run(Thread.java:841)
10-15 06:33:05.394: E/AndroidRuntime(1322): Caused by: java.lang.NullPointerException
10-15 06:33:05.394: E/AndroidRuntime(1322):     at com.zanqi.datatolistview.MainActivity$ProgressTask.doInBackground(MainActivity.java:85)
10-15 06:33:05.394: E/AndroidRuntime(1322):     at com.zanqi.datatolistview.MainActivity$ProgressTask.doInBackground(MainActivity.java:1)
10-15 06:33:05.394: E/AndroidRuntime(1322):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
10-15 06:33:05.394: E/AndroidRuntime(1322):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-15 06:33:05.394: E/AndroidRuntime(1322):     ... 4 more
10-15 06:33:06.322: E/WindowManager(1322): android.view.WindowLeaked: Activity com.zanqi.datatolistview.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{5282e178 V.E..... R....... 0,0-1664,192} that was originally added here  
10-15 06:33:06.322: E/WindowManager(1322):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:348)
10-15 06:33:06.322: E/WindowManager(1322):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
10-15 06:33:06.322: E/WindowManager(1322):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
10-15 06:33:06.322: E/WindowManager(1322):  at android.app.Dialog.show(Dialog.java:286)
10-15 06:33:06.322: E/WindowManager(1322):  at com.zanqi.datatolistview.MainActivity$ProgressTask.onPreExecute(MainActivity.java:66)
10-15 06:33:06.322: E/WindowManager(1322):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
10-15 06:33:06.322: E/WindowManager(1322):  at android.os.AsyncTask.execute(AsyncTask.java:535)
10-15 06:33:06.322: E/WindowManager(1322):  at com.zanqi.datatolistview.MainActivity.onCreate(MainActivity.java:44)
10-15 06:33:06.322: E/WindowManager(1322):  at android.app.Activity.performCreate(Activity.java:5231)
10-15 06:33:06.322: E/WindowManager(1322):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-15 06:33:06.322: E/WindowManager(1322):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
10-15 06:33:06.322: E/WindowManager(1322):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
10-15 06:33:06.322: E/WindowManager(1322):  at android.app.ActivityThread.access$800(ActivityThread.java:135)
10-15 06:33:06.322: E/WindowManager(1322):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
10-15 06:33:06.322: E/WindowManager(1322):  at android.os.Handler.dispatchMessage(Handler.java:102)
10-15 06:33:06.322: E/WindowManager(1322):  at android.os.Looper.loop(Looper.java:136)
10-15 06:33:06.322: E/WindowManager(1322):  at android.app.ActivityThread.main(ActivityThread.java:5017)
10-15 06:33:06.322: E/WindowManager(1322):  at java.lang.reflect.Method.invokeNative(Native Method)
10-15 06:33:06.322: E/WindowManager(1322):  at java.lang.reflect.Method.invoke(Method.java:515)
10-15 06:33:06.322: E/WindowManager(1322):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-15 06:33:06.322: E/WindowManager(1322):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-15 06:33:06.322: E/WindowManager(1322):  at dalvik.system.NativeStart.main(Native Method)

这是我的代码:

public class MainActivity extends ListActivity {

    private Context context; 
    private static String url = "http://172.22.112.190:8080/Qproject/servlet/Qaction?action_flag=find"; 
    private static final String phonenumber = "Number"; 
    private static final String peoplenumber = "Info"; 
    private static final String remarks = "Remarks"; 
    private static final String status = "status"; 

    ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>(); 

    ListView lv; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
        new ProgressTask(MainActivity.this).execute(); 
    } 


    private class ProgressTask extends AsyncTask<String, Void, Boolean> { 

        private ProgressDialog dialog; 

        private ListActivity activity; 

        private Context context; 

        // private List<Message> messages; 

        public ProgressTask(ListActivity activity) { 
            this.activity = activity; 
            context = activity; 
            dialog = new ProgressDialog(context); 
        } 

        protected void onPreExecute() { 
            this.dialog.setMessage("Progress start"); 
            this.dialog.show(); 
        } 

        @Override 
        protected void onPostExecute(final Boolean success) { 
            if (dialog!=null && dialog.isShowing()){
                dialog.cancel();
            }
            ListAdapter adapter = new SimpleAdapter(context, jsonlist,
                    R.layout.list_item, 
                    new String[] {phonenumber, peoplenumber, remarks, status}, 
                    new int[] {R.id.vehicleType, R.id.vehicleColor, R.id.fuel,
                               R.id.status });
            setListAdapter(adapter); 
            //select single ListView item 
            lv = getListView();
        }

        protected Boolean doInBackground(final String... args) { 
            JSONParser jParser = new JSONParser();

            // get JSON data from URL 
            JSONArray json = jParser.getJSONFromUrl(url);
            for (int i = 0; i < json.length(); i++) { 
                try { 
                    JSONObject c = json.getJSONObject(i); 
                    String number = c.getString(phonenumber); 
                    String info = c.getString(peoplenumber); 
                    String remarkss = c.getString(remarks); 
                    String statuss = c.getString(status); 

                    HashMap<String, String> map = new HashMap<String, String>(); 
                    // Add child node to HashMap key & value 
                    map.put(phonenumber, number); 
                    map.put(peoplenumber, info); 
                    map.put(remarks, remarkss); 
                    map.put(status, statuss); 
                    jsonlist.add(map); 
                } catch (JSONException e) { 
                    e.printStackTrace(); 
                }
            } 
            return null; 
        }
    }
}



public class JSONParser {

    static InputStream iStream = null; 
    static JSONArray jarray = null; 
    static JSONObject Jasonobject = null;
    static String json = ""; 

    public JSONParser() { } 

    public JSONArray getJSONFromUrl(String url) { 
        StringBuilder builder = new StringBuilder(); 
        HttpClient client = new DefaultHttpClient(); 
        HttpGet httpGet = new HttpGet(url); 
        try { 
            HttpResponse response = client.execute(httpGet); 
            StatusLine statusLine = response.getStatusLine(); 
            int statusCode = statusLine.getStatusCode(); 
            if (statusCode == 200) { 
                HttpEntity entity = response.getEntity(); 
                InputStream content = entity.getContent(); 
                BufferedReader reader = new BufferedReader(new InputStreamReader(content)); 
                String line; 
                while ((line = reader.readLine()) != null) { 
                    builder.append(line); 
                } 
            } else { 
                Log.e("==>", "Failed to download file"); 
            } 
        } catch (ClientProtocolException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        }

        // Parse String to JSON object 
        try { 
            jarray = new JSONArray( builder.toString());
        } catch (JSONException e) { 
            Log.e("JSON Parser", "Error parsing data " + e.toString()); 
        }

        // return JSON Object 
        return jarray; 
    }

}

6 个答案:

答案 0 :(得分:1)

问题是有两种不同类型的JSON:数组和对象。数组在外层有[]个圆形,对象有{}个圆形。

在Java世界中,Object是每个类的超类。如果JSON库是明智的,那么JSONObject将是JSONArray的超类,并且您可以将JSONObject用于所有内容。不幸的是,它并非如此;并且你必须知道你正在解析的是一个数组或一个对象,以决定是将它放入JSONArray还是JSONObject

您获得的错误是因为您正在阅读此JSON:

{"table"...   }

并尝试将其解释为JSONArray,当它真的是JSONObject时。如果您始终要从服务器获取相同类型的数据,则只需将您要解析的内容类型更改为JSONObject即可。如果它有时是一个,有时是另一个,你需要一些恶作剧来解析它之前是什么,或者try / catch块先尝试一个然后另一个。< / p>

但通常情况下,您会收到特定格式的数据,并且知道您将获得哪些数据。

答案 1 :(得分:0)

试试这段代码它会对你有所帮助,它对我有用。

 InputStream mIs = null;
            String result = "";
            JSONArray jArrayEvent = null;
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                mIs = entity.getContent();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
          try{
                BufferedReader bufferReader = new BufferedReader(new InputStreamReader(mIs,"iso-8859-1"),8);
                StringBuilder stringBuilder = new StringBuilder();
                String line = null;
                while ((line = bufferReader.readLine()) != null) {
                    if(line.trim().equals("\n"))
                        continue;
                    stringBuilder.append(line + "\n");
                }
                mIs.close();
                result=stringBuilder.toString();
            }catch(Exception e){

                Log.e("log_tag", "Error converting result "+e.toString());
            }
            try {
                jArrayEvent = new JSONArray(result);
            } catch (JSONException e) {

                e.printStackTrace();
            }

答案 2 :(得分:0)

好像你的json有问题 从服务器你得到jsonObject像{ .... ..... ... } 在这一行中,你尝试转换数组,这是你得到的例外

JSONArray json = jParser.getJSONFromUrl(url);

只需检查你的json并将其转换为适当的JSONObjects和JSONArrays。

答案 3 :(得分:0)

您从URL解析的JSON不是JSONArray格式,而是JSONObject格式。

{"table2":[ ... ]}

前面的花括号告诉你它是一个对象。 "table2"是此对象的第一个属性,它的值是一个数组 - 可能是您想要的数组。

您可以通过此方式获取数组(在您上一个try子句中的JSONParser中):

Jasonobject = new JSONObject(builder.toString());
jarray = Jasonobject.getJSONArray("table2");

这应该会给你你的数组。

顺便说一句,它是Java中的编码标准,用于命名驼峰大小写的变量,从小写字母开始。因此,为了编写漂亮的代码,您可以像这样重命名JSONObject变量:

static JSONObject jasonObject = null;

答案 4 :(得分:0)

 String str = jParser.getJSONFromUrl(url);
 JSONObject Jsonobject = new JSONObjectstr );
 jarray = Jsonobject .getJSONArray("table2");

答案 5 :(得分:0)

试试这段代码,可能适合你

JSONObject table = jParser.getJSONFromUrl(url);
    JSONArray json = table.getJSONArray("table2");
    for (int i = 0; i < json.length(); i++) {
              try { 
                        JSONObject c = json.getJSONObject(i); 
                        String number = c.getString(phonenumber); 
                        String info = c.getString(peoplenumber); 
                        String remarkss = c.getString(remarks); 
                        String statuss = c.getString(status); 

                        HashMap<String, String> map = new HashMap<String, String>(); 
                        // Add child node to HashMap key & value 
                        map.put(phonenumber, number); 
                        map.put(peoplenumber, info); 
                        map.put(remarks, remarkss); 
                        map.put(status, statuss); 
                        jsonlist.add(map); 
                    } catch (JSONException e) { 
                        e.printStackTrace(); 
                    }
    }

我认为你在jsonObject中有jasonArray