JSONException:其中;串GT;不能转换为JSONObject的使用JSON阵列的帮助 [英] JSONException:<String>cannot be converted to JSONObject with helps of JSON Array
问题描述
$ 错误 :: JSONException:JSON字符串不能转换为
JSONObject的与帮助JSON阵列
块引用>这是导入库
进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口的java.util.ArrayList;
进口的java.util.HashMap;
进口的java.util.Map;进口org.apache.http.Htt presponse;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.annotation.Sup pressLint;
进口android.app.Activity;
进口android.util.Log;
进口android.view.Menu;
进口android.widget.ListView;
进口android.widget.SimpleAdapter;
进口android.widget.Toast;activity_main.xml中文件
&LT;的RelativeLayout的xmlns:机器人=http://schemas.android.com/apk/res/android
的xmlns:工具=http://schemas.android.com/tools
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:paddingBottom会=@扪/ activity_vertical_margin
机器人:paddingLeft =@扪/ activity_horizontal_margin
机器人:paddingRight =@扪/ activity_horizontal_margin
机器人:paddingTop =@扪/ activity_vertical_margin
工具:上下文=MainActivity。&GT;&LT; ListView控件
机器人:ID =@ + ID / ListView1的
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:layout_alignParentTop =真
机器人:layout_centerHorizontal =真
机器人:layout_marginTop =14dp&GT;
&LT; /&的ListView GT;
Internet权限是这里
&LT;使用许可权的android:NAME =android.permission.INTERNET对/&GT;
错误
请给我答案如何获得多个值使用这种code,并显示到我的ListView这是我MainActivity.java类文件。
公共类MainActivity扩展活动
{
私人字符串jsonResult;
私人字符串URL =YOUR_PHP_FILE_URL;
私人的ListView ListView的;
@覆盖
保护无效的onCreate(捆绑savedInstanceState)
{
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main);
ListView控件=(ListView控件)findViewById(R.id.listView1);
accessWebService();
} @覆盖
公共布尔onCreateOptionsMenu(菜单菜单)
{
//充气菜单;如果是present这增加了项目操作栏。
。getMenuInflater()膨胀(R.menu.main,菜单);
返回true;
} //异步任务访问Web
@燮pressLint(NewApi)
私有类JsonReadTask扩展的AsyncTask&LT;弦乐,太虚,字符串&GT;
{
@覆盖
保护字符串doInBackground(字符串... PARAMS)
{
HttpClient的HttpClient的=新DefaultHttpClient();
HttpPost httppost =新HttpPost(PARAMS [0]);
尝试
{
HTT presponse响应= httpclient.execute(httppost);
。jsonResult = inputStreamToString(response.getEntity()的getContent())的toString();
}
赶上(ClientProtocolException E)
{
e.printStackTrace();
}
赶上(IOException异常E)
{
e.printStackTrace();
}
返回null;
} 私人的StringBuilder inputStreamToString(InputStream为)
{
串rLine =;
StringBuilder的答案=新的StringBuilder();
RD的BufferedReader =新的BufferedReader(新的InputStreamReader(是)); 尝试
{
而((rLine = rd.readLine())!= NULL)
{
answer.append(rLine);
Log.d(answer.toString(),字符串生成器类的中频环);
}
}
赶上(IOException异常E)
{
// e.printStackTrace();
Toast.makeText(getApplicationContext(),错误...+ e.toString(),Toast.LENGTH_LONG).show();
Log.d(answer.toString(),字符串生成器类中的其他部分);
}
返回的答案;
} @覆盖
保护无效onPostExecute(字符串结果)
{
ListDrwaer();
}
} //结束异步任务 公共无效accessWebService()
{
JsonReadTask任务=新JsonReadTask();
//通行证的URL字符串数组值
task.execute(新的String [] {URL});
} //建立列表视图哈希集合
公众和LT; jsonResult&GT;无效ListDrwaer()
{
ArrayList的&LT;地图&LT;字符串,字符串&GT;&GT;用户列表=新的ArrayList&LT;地图&LT;字符串,字符串&GT;&GT;();
Log.d(userList.toString()启动的JSONObject); 尝试
{
Log.d(启动试块,以前的JSONObject); JSONObject的jsonResponse =新的JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.getJSONArray(USER_INFO); Log.d(jsonMainNode.toString()启动的JSONObject); 的for(int i = 0; I&LT; jsonMainNode.length();我++)
{
JSONObject的jsonChildNode = jsonMainNode.getJSONObject(I)
字符串ID = jsonChildNode.optString(ID);
字符串名称= jsonChildNode.optString(姓名:);
字符串email = jsonChildNode.optString(电子邮件:);
字符串手机= jsonChildNode.optString(手机);
字符串密码= jsonChildNode.optString(密码);
字符串输出= ID + - +姓名+ - +电子邮件+ - +手机+ - +密码;
userList.add(在CreateEmployee(USER_INFO,输出));
Log.d(jsonChildNode.toString()内启动的JSONObject For循环);
}
}
赶上(JSONException E)
{
Toast.makeText(getApplicationContext(),错误+ e.toString(),Toast.LENGTH_SHORT).show();
Log.e(log_tag,失败的数据:\\ n+ jsonResult);
} SimpleAdapter simpleAdapter =新SimpleAdapter(这一点,用户列表,android.R.layout.simple_list_item_1,新的String [] {USER_INFO},新的INT [] {android.R.id.text1});
listView.setAdapter(simpleAdapter);
} 私人的HashMap&LT;字符串,字符串&GT;在CreateEmployee(字符串名称,串号)
{
HashMap的&LT;字符串,字符串&GT; employeeNameNo =新的HashMap&LT;字符串,字符串&GT;();
employeeNameNo.put(姓名,号码);
返回employeeNameNo;
}
}
解决方案确定你所得到的错误是很普通的,错误本身会告诉你在做什么错
$错误:: JSONException:JSON字符串不能转换为JSONObject的使用JSON阵列的帮助,
块引用>我相信你在JSON数据串,
伪数据
,因为它是在你试图读出双引号中的JSONObject的
。
这不是一个的JSONObject
但字符串
基本类型,在解析
JSON
你需要发挥注意什么是对象
,阵列
和基本型
的JSONObject
总是会在
封闭式{}
所以这次再presents一个括号内的数据是一个JSONObject,
例如===>JSONObject的JSON = jsonArray.getJSONObject(I)
或
JSONObject的JSON =新的JSONObject(JSON数据);
JSONArray将始终放在
[]
所以这次再presents一个方括号内的数据是一个JSONArray,
例如==>`json.getJSONArray(jsonArray的名字);原始型
布尔
想这isSelected:真
要么
isSelected:假的
整数
想这someInt:12
字符串
想这someString:字符串值
你可以看到你的问题是,你需要从
JSON对象
JSON
字符串区分p>$ Error:: JSONException:json string cannot be converted to JSONObject with helps of JSON Array
This is Import libraries
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 file
<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 Permission is Here
<uses-permission android:name="android.permission.INTERNET" />
error
Please give me Answer How to get Multiple Values Using this Code and show into my ListViewThis Is my MainActivity.java class file.
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; } }
解决方案ok the error you are getting is very generic, error itself tells what you are doing wrong
$ Error:: JSONException:json string cannot be converted to JSONObject with helps of JSON Array,
I believe you have string in the JSON data,
"dummy data"
as it is in double quotes which you are trying to read as aJSONObject
. It is not aJSONObject
but aString
primitive type,while parsing
JSON
you need to play attention to what is aObject
,Array
andprimitive-type
JSONObject
will always be enclosed in
{ }
so this represents that data inside a parentheses is a JSONObject, Example===>JSONObject json = jsonArray.getJSONObject(i)
or
JSONObject json = new JSONObject("JSON DATA"); JSONArray
will always be enclosed in
[ ]
so this represents that data inside a square bracket is a JSONArray, Example==> `json.getJSONArray("name of jsonArray");Primitive-type
Boolean
would like this"isSelected":true or "isSelected":false
Integer
would like this"someInt":12
String
would like this"someString":"String value"
as you can see where your problem is, you need to distinguish between
JSON
String fromJSON Object
这篇关于JSONException:其中;串GT;不能转换为JSONObject的使用JSON阵列的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!