2016-01-28 2 views
0

$ Error:: JSONException:json string cannot be converted to JSONObject with helps of JSON ArrayJSONException: <String> не могут быть преобразованы в JSONObject с подсказками JSON массива

Это Импорт библиотеки

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.Map; 

import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.os.AsyncTask; 
import android.os.Bundle; 
import android.annotation.SuppressLint; 
import android.app.Activity; 
import android.util.Log; 
import android.view.Menu; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.Toast; 

activity_main.xml файл

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context=".MainActivity" > 

<ListView 
    android:id="@+id/listView1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="14dp" > 
</ListView> 

Интернет разрешение Здесь

<uses-permission android:name="android.permission.INTERNET" /> 

error Пожалуйста, дайте мне ответ Как получить несколько значений с помощью этого кода и показать в моей ListView

Это мой файл класса MainActivity.java.

public class MainActivity extends Activity 
{ 
    private String jsonResult; 
    private String url = "YOUR_PHP_FILE_URL"; 
    private ListView listView; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     listView = (ListView) findViewById(R.id.listView1); 
     accessWebService(); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) 
    { 
      // Inflate the menu; this adds items to the action bar if it is present. 
      getMenuInflater().inflate(R.menu.main, menu); 
      return true; 
    } 

    // Async Task to access the web 
    @SuppressLint("NewApi") 
    private class JsonReadTask extends AsyncTask<String, Void, String> 
    { 
     @Override 
     protected String doInBackground(String... params) 
     { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(params[0]); 
      try 
      { 
       HttpResponse response = httpclient.execute(httppost); 
       jsonResult = inputStreamToString(response.getEntity().getContent()).toString(); 
      } 
      catch (ClientProtocolException e) 
      { 
       e.printStackTrace(); 
      } 
      catch (IOException e) 
      { 
       e.printStackTrace(); 
      } 
      return null; 
     } 

     private StringBuilder inputStreamToString(InputStream is) 
     { 
      String rLine = ""; 
      StringBuilder answer = new StringBuilder(); 
      BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 

      try 
      { 
       while ((rLine = rd.readLine()) != null) 
       { 
        answer.append(rLine); 
        Log.d(answer.toString(), "String Builder Class in IF Loop"); 
       } 
      } 
      catch (IOException e) 
      { 
       // e.printStackTrace(); 
       Toast.makeText(getApplicationContext(),"Error..." + e.toString(), Toast.LENGTH_LONG).show(); 
       Log.d(answer.toString(), "String Builder Class in Else Part"); 
      } 
      return answer; 
     } 

     @Override 
     protected void onPostExecute(String result) 
     { 
      ListDrwaer(); 
     } 
    }// end async task 

    public void accessWebService() 
    { 
     JsonReadTask task = new JsonReadTask(); 
      // passes values for the urls string array 
      task.execute(new String[] { url }); 
    } 

    // build hash set for list view 
    public <jsonResult> void ListDrwaer() 
    { 
     ArrayList<Map<String,String>> userList = new ArrayList<Map<String, String>>(); 
     Log.d(userList.toString(), "Starting JSONObject"); 

     try 
     {    
      Log.d("Starting Try Block", "Before JSONObject"); 

      JSONObject jsonResponse = new JSONObject(jsonResult); 
      JSONArray jsonMainNode = jsonResponse.getJSONArray("user_info"); 

      Log.d(jsonMainNode.toString(), "Starting JSONObject"); 

      for (int i = 0; i < jsonMainNode.length(); i++) 
      { 
       JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); 
       String id = jsonChildNode.optString("Id:"); 
       String name = jsonChildNode.optString("Name:"); 
       String email = jsonChildNode.optString("Email:"); 
       String phone = jsonChildNode.optString("Phone:"); 
       String password = jsonChildNode.optString("Password"); 
       String outPut = id + "-" + name+ "-" + email+ "-" + phone+ "-" + password; 
       userList.add(createEmployee("user_info", outPut)); 
       Log.d(jsonChildNode.toString(), "Starting JSONObject inside For Loop"); 
      } 
     } 
     catch (JSONException e) 
     { 
      Toast.makeText(getApplicationContext(), "Error" + e.toString(),Toast.LENGTH_SHORT).show(); 
      Log.e("log_tag", "Failed data was:\n" + jsonResult); 
     } 

     SimpleAdapter simpleAdapter = new SimpleAdapter(this, userList,android.R.layout.simple_list_item_1,new String[] { "user_info" }, new int[] { android.R.id.text1 }); 
     listView.setAdapter(simpleAdapter); 
    } 

    private HashMap<String, String> createEmployee(String name, String number) 
    { 
     HashMap<String, String> employeeNameNo = new HashMap<String, String>(); 
     employeeNameNo.put(name, number); 
     return employeeNameNo; 
    } 
} 
+1

Вероятно, пытаясь преобразовать JSONArray в JSONObject. show 'jsonResult' String также с вопросом –

+0

Не могли бы вы опубликовать полный журнал ошибок? Как отметил @ ρяσѕρєяK, возможно, вы пытаетесь преобразовать JSONArray в JSONObject или может быть какой-то другой формат текста, например html. У меня была та же проблема, когда я попытался разобрать сообщение '404' html в' JSONObject'. :) – theapache64

+0

Добавьте результат LogCat – Pitty

ответ

1

нормально ошибка, вы получаете очень общий характер, ошибка сама говорит, что вы делаете неправильно

$ Error:: JSONException:json string cannot be converted to JSONObject with helps of JSON Array,

Я считаю, что у вас есть строка в данных JSON, "dummy data" как в двойных кавычках который вы пытаетесь читать как JSONObject. Это не JSONObject но String примитивный тип,

при разборе JSON вам нужно обратить внимание на то, что это Object, Array и primitive-type

JSONObject 

всегда будет заключен в { } так что это представляет, что данные внутри скобок является JSONObject, Пример ===>

JSONObject json = jsonArray.getJSONObject(i) 

или

JSONObject json = new JSONObject("JSON DATA"); 


JSONArray 

всегда будет заключен в [ ] так что это представляет, что данные внутри квадратных скобок является JSONArray, Пример ==> `JSON.getJSONArray ("имя jsonArray");

Primitive-type 

Boolean хотел бы это

"isSelected":true 
or 
"isSelected":false 

Integer хотел бы это

"someInt":12 

String хотел бы этот

"someString":"String value" 

как вам может видеть, где ваша проблема, вы должны различать JSON строки из JSON Object

0

Удалить эту линию, потому что вы преобразовать JSON строки в объект Json

JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);