2013-10-12 6 views
-1

У меня возникли большие проблемы с разбором данных JSON. Я всегда получаю эту ошибку:Анализ данных JSON Android

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> 

main.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> 
+0

Вы можете разместить свой JSON. – Raghunandan

ответ

0

В вашей ошибке говорится, что вы получаете String вместе с вашим объектом, который, скорее всего, может быть ошибкой, создаваемой скриптами на стороне сервера. Эта строка не может быть преобразована в объект json. Удостоверьтесь, что это не вызывает никаких ошибок. Если вы хотите, чтобы я прояснил многое об этом, просто распечатайте это System.out.println(sb.toString()); сразу после этого фрагмента кода в своем классе JSONParser и дайте мне знать.

while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
+0

такая же ошибка снова. Я даже не вижу эту ценность на консоли ... –

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

Я попробовал и оснастки на моем телефоне

enter image description here

+0

Спасибо, человек! Он, наконец, работает ... –

+0

@ja_zg приветствуется, и вы можете отметить ответ как принятый – Raghunandan

Смежные вопросы