org.json.JSONArray не может быть преобразован в JSONObject

Я новичок в Android, и я использую JSON для получения данных, но я получаю эту ошибку org.json.JSONArray не может быть преобразован в JSONObject.How следует этот Решение, но все же я получаю ошибку

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class MainActivity extends ActionBarActivity {

String myJSON;

private static final String TAG_RESULTS="result";
private static final String TAG_USERNAME="username";
private static final String TAG_NAME = "message_recd";
private static final String TAG_ADD ="message_sent";

JSONArray peoples = null;

ArrayList<HashMap<String, String>> personList;

ListView list;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();

}


protected void showList(){
try {
JSONArray peoples = new JSONArray(myJSON);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name=null, address=null, username=null;

if(c.has("message_recd"))
name = c.getString("message_recd");
else if(c.has("message_sent"))
address = c.getString("message_sent");
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_ADD,address);
personList.add(persons);
}

ListAdapter adapter = new SimpleAdapter(
MainActivity.this, personList, R.layout.list_item,
new String[]{TAG_NAME,TAG_ADD},
new int[]{R.id.name, R.id.address}
);

list.setAdapter(adapter);

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

public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{





@Override
protected String doInBackground(String... params) {

Intent intent1 = getIntent();
String fName = intent1.getStringExtra("fname");

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", fName));
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://10.0.2.2/progress_card/testing.php");

// Depends on your web service
httppost.setHeader("Content-type", "application/json");

InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();

String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}

@Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}


}

Logcat:

09-22 06:45:38.035: W/System.err(6513): org.json.JSONException: Value [{"message_recd":"asdadasda"},{"message_recd":"hello"},{"message_recd":"how r u"},{"message_recd":"hello\n"},{"message_recd":"hello"},{"message_recd":"1"},{"message_recd":"qd"},{"message_recd":"1"},{"message_recd":"hello12"},{"message_recd":"hello again"},{"message_recd":"hey whtas up"},{"message_recd":"jhkwdfjdw"},{"message_recd":"is it working"},{"message_recd":"qw"},{"message_recd":"sdfsdfsdfsadf"},{"message_recd":"qwertyuiop"},{"message_recd":"aaaa"},{"message_sent":"hey whtas up"}] of type org.json.JSONArray cannot be converted to JSONObject
09-22 06:45:38.085: W/System.err(6513):     at org.json.JSON.typeMismatch(JSON.java:111)
09-22 06:45:38.085: W/System.err(6513):     at org.json.JSONObject.<init>(JSONObject.java:159)
09-22 06:45:38.085: W/System.err(6513):     at org.json.JSONObject.<init>(JSONObject.java:172)
09-22 06:45:38.085: W/System.err(6513):     at com.example.fetchdata.MainActivity.showList(MainActivity.java:55)
09-22 06:45:38.085: W/System.err(6513):     at com.example.fetchdata.MainActivity$1GetDataJSON.onPostExecute(MainActivity.java:130)
09-22 06:45:38.095: W/System.err(6513):     at com.example.fetchdata.MainActivity$1GetDataJSON.onPostExecute(MainActivity.java:1)
09-22 06:45:38.095: W/System.err(6513):     at android.os.AsyncTask.finish(AsyncTask.java:632)
09-22 06:45:38.095: W/System.err(6513):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
09-22 06:45:38.095: W/System.err(6513):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
09-22 06:45:38.095: W/System.err(6513):     at android.os.Handler.dispatchMessage(Handler.java:102)
09-22 06:45:38.095: W/System.err(6513):     at android.os.Looper.loop(Looper.java:136)
09-22 06:45:38.095: W/System.err(6513):     at android.app.ActivityThread.main(ActivityThread.java:5001)
09-22 06:45:38.095: W/System.err(6513):     at java.lang.reflect.Method.invokeNative(Native Method)
09-22 06:45:38.095: W/System.err(6513):     at java.lang.reflect.Method.invoke(Method.java:515)
09-22 06:45:38.095: W/System.err(6513):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
09-22 06:45:38.095: W/System.err(6513):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
09-22 06:45:38.145: W/System.err(6513):     at dalvik.system.NativeStart.main(Native Method)

Выход JSON в Java

[{"message_recd":"asdadasda"},{"message_recd":"hello"},{"message_recd":"how r u"},{"message_recd":"hello\n"},{"message_recd":"hello"},{"message_recd":"1"},{"message_recd":"qd"},{"message_recd":"1"},{"message_recd":"hello12"},{"message_recd":"hello again"},{"message_recd":"hey whtas up"},{"message_recd":"jhkwdfjdw"},{"message_recd":"is it working"},{"message_recd":"qw"},{"message_recd":"sdfsdfsdfsadf"},{"message_recd":"qwertyuiop"},{"message_recd":"aaaa"},{"message_sent":"hey whtas up"}]

Код Myphp

<?php

define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','progress_card');

$con = mysqli_connect(HOST,USER,PASS,DB);

$sql1 = "select * from student_detail where parentusername='suyash1'";
$res1 = mysqli_query($con,$sql1);

$row1=mysqli_fetch_array($res1);

$cl=$row1['class']."-".$row1['section'];
$sql2="select * from teachers where classassign='$cl'";
$res2 = mysqli_query($con,$sql2);

$row2=mysqli_fetch_array($res2);

$to=$row2['email'];
$from=$row1['parentemail'];



$result = array();

$sql = "select * from messages where to_email='".$to."' and from_email='".$from."'";
$res = mysqli_query($con,$sql);

while($row = mysqli_fetch_array($res))
{
array_push($result,array('message_recd'=>$row['message']));
}

$sqlw = "select * from messages where from_email='".$to."' and to_email='".$from."'";
$resw = mysqli_query($con,$sqlw);

while($row5 = mysqli_fetch_array($resw))
{

array_push($result,array('message_sent'=>$row5['message']));
}

//array_push($result,array('message_sent'=>"dfdsghdfgddfgdsd"));
//array_push($result,array('message_sent'=>"sfdsflkufhskfhdskjfsfssadfadsffsafasfsfsadfafsaf"));

//array_push($result,array('message_recd'=>$row1['parentemail'],'message_sent'=>$row2['email']));

echo json_encode($result);

mysqli_close($con);

?>

-4

Решение

Измените функцию showList () следующим кодом:

 protected void showList(){
try {
JSONArray peoples = new JSONArray(myJSON);

for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name=null, address=null;
if(c.has("message_recd"))
name = c.getString("message_recd");
else if(c.has("message_sent"))
address = c.getString("message_sent");

HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_ADD,address);
personList.add(persons);
}

ListAdapter adapter = new SimpleAdapter(
MainActivity.this, personList, R.layout.list_item,
new String[]{TAG_NAME,TAG_ADD},
new int[]{R.id.name, R.id.address}
);

list.setAdapter(adapter);

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

Другие решения

Ваш вывод — массив json, а не объект json. Вы должны делать —

JSONArray jsonArray = new JSONArray(myJSON);

Теперь переберите этот массив json, чтобы получить значения.

0

Содержание в [] означает, что это JSONArray, а содержимое заключено в {} означает, что это JSONObject.
Ваш ответ Json начинается с [ поэтому его массив не JSONObject, поэтому вы должны изменить

JSONObject jsonObj = new JSONObject(myJSON);

в

JSONArray  jArray=new JSONArray (myJSON);

Теперь вы можете пройти JSONArray

for(int i=0;i<jArray.length();i++){
JSONObject people =jArray.getJSONObject(i);
// Now get all required values from people (JSONObject)
}
0

Ваш вывод — массив JSON, а не объект, попробуйте это решение

изменить код ниже

JSONObject jsonObj = new JSONObject(myJSON);
JSONArray  peoples = jsonObj.getJSONArray(TAG_RESULTS);

в

JSONArray peoples = new JSONArray(myJSON);
0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector