-1

我在解析 JSON 数据时遇到了大问题。我总是收到这个错误:

error parsing data org.json.JSONException: Value <!doctype of type java.Lang.String cannot be       
converted to JSONObject

我需要获取 JSON 数据并将其列在 ListView 中。我需要列出姓名、姓氏、数字和图片,因此我将非常感谢有关从 url 加载图像的一些建议,但现在主要问题是我总是收到我提到的错误。

这是代码,JSONParsing.java:

public class JSONParsing extends ListActivity {
private static String URL = "http://androidtest.apiary.io/get-users";

private static String TAG_USERS = "users";
private static String TAG_NAME = "name";
private static String TAG_LAST_NAME = "last_name";
private static String TAG_PH_NUM = "number";

JSONArray users = null;

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

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, 
                                                                          String>>();

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject jobj = jParser.getJSONFromUrl(URL);

    try {
        // Getting Array of Contacts
        users = jobj.getJSONArray(TAG_USERS);

        // looping through All Contacts
        for(int i = 0; i < users.length(); i++){
            JSONObject job = users.getJSONObject(i);

            // Storing each json item in variable
            String name = job.getString(TAG_NAME);
            String lastName = job.getString(TAG_LAST_NAME);
            String number = job.getString(TAG_NAME);

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_NAME, name);
            map.put(TAG_LAST_NAME, lastName);
            map.put(TAG_PH_NUM, number);

            // adding HashList to ArrayList
            contactList.add(map);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    ListAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.list_item,
            new String[] { TAG_NAME + " " + TAG_LAST_NAME, TAG_PH_NUM }, new
                             int[] {
                    R.id.name, R.id.email, R.id.mobile });

    setListAdapter(adapter);

}


}

和 JSONParser.java:

public class JSONParser {

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

// constructor
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 parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

还有 xml 的 list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:context=".JSONParsing" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#43bd00"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/lastName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textColor="#acacac" />

    <TextView
        android:id="@+id/number"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="left"
        android:textColor="#acacac"
        android:textStyle="bold" />

</LinearLayout>

</LinearLayout>

主.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".JSONParsing" >


<ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

</LinearLayout>
4

2 回答 2

0

您的错误表明您正在获取 String 以及您的对象,这很可能是服务器端脚本引发的错误。该字符串无法转换为 json 对象。确保它不会引发任何错误。如果您希望我对此进行更多说明,只需System.out.println(sb.toString()); 在您的JSONParser类中的这段代码之后立即打印它并让我知道。

while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
于 2013-10-12T14:41:23.347 回答
0

您发布的链接中的 json

{
    "users": [
        {
            "name": "Hyper",
            "last_name": "Active",
            "image": "http://thehyperactive.com/logo.png",
            "number": 098423239
        },
        {
            "name": "Igor",
            "last_name": "Švehla",
            "image": "http://www.webstrategija.com/ws/adminmax/images/upload/10/igor_svehla_web.jpg",
            "number": 098523239
        },
        {
            "name": "Hrvoje",
            "last_name": "Horvat",
            "image": "http://www.rhein-neckar-loewen.de/images/spieler_2010/hrvoje-horvat.jpg",
            "number": "098423240"
        },
        {
            "name": "Ivan",
            "last_name": "Aksijentijevič Podvorski",
            "image": "http://dalje.com/slike/slike_3/r1/g2009/m02/x213194805338620316_1.jpg",
            "number": 098423241
        },
        {
            "name": "Gasper",
            "last_name": "Sōtsy",
            "image": "http://m3.licdn.com/mpr/pub/image-0em6ZpPcOdZ5lNMcu6cP5vOTrPiLzZFqRDckeCHGr4zB-2pG0emkiNscr_KvzvxVejSB/gasper-sopi.jpg",
            "number": 098423242
        }
    ]
}

试试下面

 HttpClient httpclient = new DefaultHttpClient();
 httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
 HttpGet request = new HttpGet("http://androidtest.apiary.io/get-users");
 HttpResponse response = httpclient.execute(request);
 HttpEntity resEntity = response.getEntity();
 String _response=EntityUtils.toString(resEntity); // content will be consume only once
 Log.i(".......",_response);
 JSONObject json = new JSONObject(_response);
 JSONArray jarray = json.getJSONArray("users");
    for(int i=0;i<jarray.length();i++)
    {
        JSONObject jb = (JSONObject) jarray.get(i);
        String name = jb.getString("name");
    }

您应该使用 asynctask 并在doInbackground

http://developer.android.com/reference/android/os/AsyncTask.html

我试过了,手机上的快照

在此处输入图像描述

于 2013-10-12T14:56:07.290 回答