1

我在我的 android 应用程序中使用 asp.net web api。但这给了我一个错误。我的返回字符串是 JSON 格式。
下面是我的日志猫

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)

这是我的测试类 Test.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;
    }

}

我在谷歌上发现数据不是 JSON 格式。根据我的日志,我的数据是 JSON 格式。所以代码有什么问题。我也使用 UTF-8 编码。但同样的问题。

4

2 回答 2

1

您正在将JSONArraya 读入JSONObject.. 您需要更改:

jArray = new JSONObject(result);

至:

JSONArray jArray = new JSONArray(result);

检查http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

于 2012-11-30T07:56:46.170 回答
1

您正在尝试转换JsonArrayJsonObject更改您的代码,因为在当前 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更改为JSONArrayas

public static JSONArray executeGet(String url) throws JSONException
于 2012-11-30T07:56:49.213 回答