Php 无法将org.json.JSONArray转换为JSONObject
我是android新手,我正在使用json获取数据,但我收到了这个错误org.json.JSONArray无法转换为JSONObject。如何遵循解决方案,但我仍然收到了错误Php 无法将org.json.JSONArray转换为JSONObject,php,android,json,android-json,Php,Android,Json,Android Json,我是android新手,我正在使用json获取数据,但我收到了这个错误org.json.JSONArray无法转换为JSONObject。如何遵循解决方案,但我仍然收到了错误 import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; i
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();
}
}
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);
?>
您的输出是json数组而不是json对象。你应该做什么-
JSONArray jsonArray = new JSONArray(myJSON);
现在循环这个json数组以获取值。包含在[]
中的内容表示它是JSONArray,而包含在{}
中的内容表示它是JSONObject。
您的Json响应以[
开头,因此它是一个数组,而不是JSONObject,因此您必须进行更改
JSONObject jsonObj = new JSONObject(myJSON);
到
现在可以遍历JSONArray了
for(int i=0;i<jArray.length();i++){
JSONObject people =jArray.getJSONObject(i);
// Now get all required values from people (JSONObject)
}
for(int i=0;i使用以下代码更改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();
}
}
protectedvoid showList(){
试一试{
JSONArray peoples=新的JSONArray(myJSON);
对于(inti=0;i您的输出是JSON数组而不是对象,请尝试此解决方案
更改以下代码
JSONObject jsonObj = new JSONObject(myJSON);
JSONArray peoples = jsonObj.getJSONArray(TAG_RESULTS);
到
你应该发布一个…付出一些努力并在Google上做一个可能重复的json格式是错误的,请检查itI am GET error-类型JSONArray中的方法getJSONArray(int)不适用于参数(String)@AnshulKhare,你在哪一行得到这个错误我在哈希映射(名称、地址)中得到错误-局部变量名称可能尚未初始化Set-String name=null,address=null;@AnshulKhare,是否已修复?使用-result=EntityUtils.toString(sb.toString());我现在有一个不同的问题,在php中我写了一个特定的用户名,但是如果我想要登录者的信息,我应该在上面的代码中做什么编辑来获取数据?
for(int i=0;i<jArray.length();i++){
JSONObject people =jArray.getJSONObject(i);
// Now get all required values from people (JSONObject)
}
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();
}
}
JSONObject jsonObj = new JSONObject(myJSON);
JSONArray peoples = jsonObj.getJSONArray(TAG_RESULTS);
JSONArray peoples = new JSONArray(myJSON);