android - 转换结果时出错 org.json.JSONException

标签 android json

I`m consuming asp.net web api in my android app. But it gives me an error. my returning string is in JSON format.
below is my log cat

11-30 12:44:02.760: W/ActivityThread(821): Application com.example.test is waiting for the debugger on port 8100...
11-30 12:44:02.811: I/System.out(821): Sending WAIT chunk
11-30 12:44:02.820: I/dalvikvm(821): Debugger is active
11-30 12:44:02.900: I/System.out(821): Debugger has connected
11-30 12:44:02.900: I/System.out(821): waiting for debugger to settle...
11-30 12:44:03.099: I/System.out(821): waiting for debugger to settle...
11-30 12:44:03.299: I/System.out(821): waiting for debugger to settle...
11-30 12:44:03.509: I/System.out(821): waiting for debugger to settle...
11-30 12:44:03.709: I/System.out(821): waiting for debugger to settle...
11-30 12:44:03.910: I/System.out(821): waiting for debugger to settle...
11-30 12:44:04.113: I/System.out(821): waiting for debugger to settle...
11-30 12:44:04.319: I/System.out(821): waiting for debugger to settle...
11-30 12:44:04.519: I/System.out(821): waiting for debugger to settle...
11-30 12:44:04.721: I/System.out(821): waiting for debugger to settle...
11-30 12:44:04.930: I/System.out(821): debugger has settled (1324)
11-30 12:46:27.210: E/log_tag(821): Error converting result org.json.JSONException: Value [{"Name":"Panadol","Batch":"B030","Id":1,"Expiry":"12\/11\/2013","Type":"Tablet","Price":"12"},{"Name":"Velosef 500mg","Batch":"B069","Id":2,"Expiry":"06\/12\/2014","Type":"Capsule","Price":"100"},{"Name":"Tandegyl 120ml","Batch":"B097","Id":3,"Expiry":"09\/08\/2015","Type":"Syrup","Price":"120"},{"Name":"Acefyl","Batch":"B78","Id":4,"Expiry":"03\/12\/2014","Type":"Syrup","Price":"50"},{"Name":"Tyno","Batch":"B79","Id":5,"Expiry":"03\/06\/2015","Type":"Syrup","Price":"48"},{"Name":"Nocid 40mg","Batch":"BN09","Id":6,"Expiry":"11\/09\/2013","Type":"Tablet","Price":"60"},{"Name":"Lipiget 100mg","Batch":"B090","Id":7,"Expiry":"09\/09\/2015","Type":"Tablet","Price":"250"}] of type org.json.JSONArray cannot be converted to JSONObject
11-30 12:46:42.319: D/dalvikvm(821): Debugger has detached; object registry had 498 entries
11-30 12:46:42.333: I/dalvikvm(821): ignoring registerObject request in thread=1
11-30 12:46:42.333: I/dalvikvm(821): ignoring registerObject request in thread=1
11-30 12:46:42.333: D/AndroidRuntime(821): Shutting down VM
11-30 12:46:42.333: W/dalvikvm(821): threadid=1: thread exiting with uncaught exception (group=0x40015560)
11-30 12:46:42.399: E/AndroidRuntime(821): FATAL EXCEPTION: main
11-30 12:46:42.399: E/AndroidRuntime(821): java.lang.NullPointerException
11-30 12:46:42.399: E/AndroidRuntime(821):  at com.example.test.Test$1$1$1.run(Test.java:63)
11-30 12:46:42.399: E/AndroidRuntime(821):  at android.os.Handler.handleCallback(Handler.java:587)
11-30 12:46:42.399: E/AndroidRuntime(821):  at android.os.Handler.dispatchMessage(Handler.java:92)
11-30 12:46:42.399: E/AndroidRuntime(821):  at android.os.Looper.loop(Looper.java:123)
11-30 12:46:42.399: E/AndroidRuntime(821):  at android.app.ActivityThread.main(ActivityThread.java:3683)
11-30 12:46:42.399: E/AndroidRuntime(821):  at java.lang.reflect.Method.invokeNative(Native Method)
11-30 12:46:42.399: E/AndroidRuntime(821):  at java.lang.reflect.Method.invoke(Method.java:507)
11-30 12:46:42.399: E/AndroidRuntime(821):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-30 12:46:42.399: E/AndroidRuntime(821):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-30 12:46:42.399: E/AndroidRuntime(821):  at dalvik.system.NativeStart.main(Native Method)

这是我的测试课 测试.java

package com.example.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;

public class Test extends Activity {

    AutoCompleteTextView acw;
    Button click;

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

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy); 

        acw=(AutoCompleteTextView)findViewById(R.id.AndroidBooks);
        click=(Button)findViewById(R.id.button1);

        final Handler threadHandler;  
        threadHandler = new Handler();

        new Thread(new Runnable(){

            @Override
            public void run() {

                final String url="http://10.0.2.2:3325/api/ProductType";

                click.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        threadHandler.post(new Runnable(){

                            @Override
                            public void run() {

                                List<String> temp=new ArrayList<String>();

                                try {
                                    JSONObject json=executeGet(url);
                                    Log.v("Response", json.toString());
                                } catch (JSONException e) {

                                    e.printStackTrace();
                                }

                            }

                        });

                    }
                });

            }

        }).start();
    }

    public static JSONObject  executeGet(String url) throws JSONException
    {
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;
        int response=0;
        HttpURLConnection connection = null; 
        try
        {
            connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestMethod("GET");
            connection.connect();
            response=connection.getResponseCode();
            is=connection.getInputStream();
        } 
        catch(Exception e)
        {
            e.printStackTrace();
            Log.e("HTTP Response", e.toString());
        }
        try
        {
            if(response==200)
            {

                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();
                result=sb.toString();

                jArray = new JSONObject(result);
            }

        }
        catch (IOException e) {
            e.printStackTrace();
        }
        catch(Exception e)
        {
            Log.e("log_tag", "Error converting result "+e.toString());
        }

        return jArray;
    }

}

I find on google that data isn`t JSON format. according to my log my data is in JSON format. so whats wrong in the code. i also use UTF-8 encoding. but same issue.

最佳答案

您正在尝试将 JsonArray 转换为 JsonObject,因此请更改您的代码,因为在当前 json 字符串中包含 JsonArray 而不是 JsonObejct 作为根元素:

 try {
      JSONArray jsonarray=executeGet(url);
      for (int i = 0; i < jsonarray.length(); ++i) {
      JSONObject jsonobject = jsonarray.getJSONObject(i);
      String str_name=jsonobject.getString("Name");
      String str_Batch=jsonobject.getString("Batch");
      String str_Id=jsonobject.getString("Id");
      String str_Expiry=jsonobject.getString("Expiry");
      String str_Type=jsonobject.getString("Type");
      String str_Price=jsonobject.getString("Price");

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

同时将 executeGet(String url) 方法的返回类型从 JsonObject 更改为 JSONArray as

public static JSONArray executeGet(String url) throws JSONException

关于android - 转换结果时出错 org.json.JSONException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13641078/

相关文章:

Android AdMob : The import com. google.ads 无法解析

android - 如何在不显示选择器的情况下打开默认相机?

java - 在ant中引用外部.jar库来构建Android java jar

java - ViewStub 没有膨胀并且布局保持空白 - Android

JQuery 的 getJSON() 未正确设置 Accept header ?

java - REST 发布请求

ruby - 将对象序列化为 JSON、XML、YAML?

Android 帐户管理器不缓存 authToken

java - MQTT 消息到 JSONObject

javascript - 遍历复杂的 JSON 对象