JSON异常:<String>无法在 JSON 数组的帮助下转换为 JSON对象
JSONException:<String>cannot be converted to JSONObject with helps of JSON Array
$ Error:: JSONException:json string cannot be converted to
JSONObject with helps of JSON Array
这是导入库
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>
已获得 Internet 许可
<uses-permission android:name="android.permission.INTERNET" />
error
请给我答案如何使用此代码获取多个值并显示到我的 ListView
这是我的 MainActivity.java class 文件。
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;
}
}
好的,您遇到的错误非常普遍,错误本身会告诉您做错了什么
$ 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
将始终包含在 { }
中,因此这表示括号内的数据是一个 JSON 对象,
例子===>
JSONObject json = jsonArray.getJSONObject(i)
或
JSONObject json = new JSONObject("JSON DATA");
JSONArray
将始终包含在 [ ]
中,因此这表示方括号内的数据是一个 JSON 数组,
示例==>`json.getJSONArray("name of jsonArray");
Primitive-type
Boolean
喜欢这个
"isSelected":true
or
"isSelected":false
Integer
喜欢这个
"someInt":12
String
喜欢这个
"someString":"String value"
如您所见,您的问题出在哪里,您需要区分 JSON
字符串和 JSON Object
删除此行,因为您将 Json 字符串转换为 Json 对象
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
$ Error:: JSONException:json string cannot be converted to JSONObject with helps of JSON Array
这是导入库
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>
已获得 Internet 许可
<uses-permission android:name="android.permission.INTERNET" />
error
请给我答案如何使用此代码获取多个值并显示到我的 ListView
这是我的 MainActivity.java class 文件。
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;
}
}
好的,您遇到的错误非常普遍,错误本身会告诉您做错了什么
$ 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
将始终包含在 { }
中,因此这表示括号内的数据是一个 JSON 对象,
例子===>
JSONObject json = jsonArray.getJSONObject(i)
或
JSONObject json = new JSONObject("JSON DATA");
JSONArray
将始终包含在 [ ]
中,因此这表示方括号内的数据是一个 JSON 数组,
示例==>`json.getJSONArray("name of jsonArray");
Primitive-type
Boolean
喜欢这个
"isSelected":true
or
"isSelected":false
Integer
喜欢这个
"someInt":12
String
喜欢这个
"someString":"String value"
如您所见,您的问题出在哪里,您需要区分 JSON
字符串和 JSON Object
删除此行,因为您将 Json 字符串转换为 Json 对象
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);