Android 如何使用Json解析器?
我将下面给出的解析器与示例Android2.2一起使用。我的例子是有效的,我没有问题。当尝试在一个使用安卓4.3的项目中使用该应用程序时,会出现一些示例。但是我的解析器行有问题Android 如何使用Json解析器?,android,json,android-parser,Android,Json,Android Parser,我将下面给出的解析器与示例Android2.2一起使用。我的例子是有效的,我没有问题。当尝试在一个使用安卓4.3的项目中使用该应用程序时,会出现一些示例。但是我的解析器行有问题 HttpResponse httpResponse = httpClient.execute(httpPost); 我检查了清单中的所有权限,所有权限都被使用了 public class JSONParser { static InputStream is = null; static JSONObj
HttpResponse httpResponse = httpClient.execute(httpPost);
我检查了清单中的所有权限,所有权限都被使用了
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
Log.d("test url" , "le request est lancé") ;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.d("test url" , "la connection etablie");
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
日志是:
11-14 10:48:38.590: ERROR/AndroidRuntime(3801): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{fr.web.tab/fr.web.profilconfiguration.AndroidJSONParsingActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
at java.net.InetAddress.getAllByName(InetAddress.java:220)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at fr.web.profilconfiguration.JSONParser.getJSONFromUrl(JSONParser.java:44)
at fr.web.profilconfiguration.AndroidJSONParsingActivity.onCreate(AndroidJSONParsingActivity.java:62)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
您正在ui线程上运行网络实时操作
HttpResponse httpResponse = httpClient.execute(httpPost);
上述语句必须位于线程
或asynctaskdoInbackground
中
在ui线程上调用异步任务new TheTask().execute()
class任务扩展异步任务{
@凌驾
受保护的Void doInBackground(Void…参数){
JSONObject jobject=getJSONFromUrl(字符串url);
返回null;
}
}
不能在主线程上使用HttpResponse
。您必须使用AsyncTask
从Web获取Json
读这篇文章
公共静态JSONObject responseForSignin(最终字符串uname,最终字符串pwd){
JSONObject jsonResponse=null;
HttpParams httpParameters=新的BasicHttpParams();
int connectionTimeout=1000*12;
int socketTimeout=1000*13;
HttpConnectionParams.setConnectionTimeout(httpParameters,connectionTimeout);
HttpConnectionParams.setSoTimeout(httpParameters,socketTimeout);
//创建一个新的HttpClient和Post头
HttpClient HttpClient=新的默认HttpClient(httpParameters);
HttpPost HttpPost=新的HttpPost(“URL”);
setHeader(“内容类型”,“应用程序/x-www-form-urlencoded”);
试一试{
//添加您的数据
List signinDetails=new ArrayList();
添加(新的BasicNameValuePair(“名称”,uname));
添加(新的BasicNameValuePair(“pwd”,pwd));
setEntity(新的UrlEncodedFormEntity(SignindDetails));
//执行HTTP Post请求
HttpResponse HttpResponse=httpClient.execute(httpPost);
Log.v(“Post状态”,“代码:”+httpResponse.getStatusLine().getStatusCode());
responseCode=httpResponse.getStatusLine().getStatusCode();
Log.e(“响应代码”,String.valueOf(“响应代码”+responseCode));
HttpEntity entity=httpResponse.getEntity();
Log.e(“实体”,String.valueOf(实体));
如果(实体!=null){
如果(实体!=null){
String ResponseBy=EntityUtils.toString(实体);
JSONTokener JSONTokener=新的JSONTokener(响应库);
jsonResponse=新的JSONObject(jsonTokener);
JSONObject response=jsonResponse.getJSONObject(“response”);
//获取响应对象内的字符串
字符串状态=response.getString(“状态”);
字符串消息=response.getString(“消息”);
}
}//如果(实体!=null)结束
}
捕获(SocketException见XP)
{
}
捕获(ConnectTimeoutException cteExp)
{
//TODO自动生成的捕捉块
}
catch(ClientProtocolException cpeExp){
//TODO自动生成的捕捉块
}
捕获(未知后异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
捕获(异常为allExp){
//TODO自动生成的捕捉块
}
返回jsonResponse;
}
试试这个
public class RequestLogInFromServer extends AsyncTask<Object, Object, Object>
{
private ProgressDialog progressDialog;
@Override
protected Object doInBackground(Object... params)
{
try {
JSONObject subscriptionResponse = CommonJsonParser.responseForSignin(uname, pwd).getJSONObject("response");
if (!(subscriptionResponse.equals(null))||!(subscriptionResponse.equals(""))) {
}
}
catch (NullPointerException e) {
// TODO Auto-generated catch block
}
catch (JSONException e) {
// TODO Auto-generated catch block
}
catch (Exception e) {
// TODO Auto-generated catch block
}
return null;
}
@Override
protected void onPostExecute(Object result)
{
if(progressDialog!=null){
progressDialog.dismiss();
}
super.onPostExecute(result);
}
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(SignInActivity.this, "", "Please wait");
super.onPreExecute();
}
}
公共类RequestLogInFromServer扩展异步任务
{
私有进程对话;
@凌驾
受保护对象doInBackground(对象…参数)
{
试一试{
JSONObject subscriptionResponse=CommonJsonParser.responseForSignin(uname,pwd).getJSONObject(“response”);
如果(!(subscriptionResponse.equals(null))| |!(subscriptionResponse.equals(“”)){
}
}
捕获(NullPointerException e){
//TODO自动生成的捕捉块
}
捕获(JSONException e){
//TODO自动生成的捕捉块
}
捕获(例外e){
//TODO自动生成的捕捉块
}
返回null;
}
@凌驾
受保护的void onPostExecute(对象结果)
{
如果(progressDialog!=null){
progressDialog.disclose();
}
super.onPostExecute(结果);
}
@凌驾
受保护的void onPreExecute(){
progressDialog=progressDialog.show(SignInActivity.this,“,”请稍候“);
super.onPreExecute();
}
}
使用AsyncTask。任何服务器请求或需要很长时间的请求都应写入后台任务不要在主线程中使用网络活动。此异常仅适用于目标为蜂巢SDK或更高版本的应用程序。在单独的线程中执行所有与网络相关的任务。您的问题将得到解决。您正在主线程中进行网络工作,这就是为什么会出现此错误。 在开发过程中,您可以使用此选项,但不能使用实时应用程序 将此代码放在setcontentView(布局)之后的oncreate方法中的活动中
您是否在清单文件中使用了网络权限?可能是重复的,请详细解释。在我的解析器中什么是params?也就是var args google。这是asynctask的doinbackground,并将您的网络相关代码移到doinbackground。@user2043602是什么让您认为接受答案是解决方案pls h
class TheTask extends AsyncTask<Void ,Void, Void>{
@Override
protected Void doInBackground(Void... params) {
JSONObject jobject =getJSONFromUrl(String url);
return null;
}
}
Caused by: android.os.NetworkOnMainThreadException
public static JSONObject responseForSignin(final String uname,final String pwd) {
JSONObject jsonResponse = null;
HttpParams httpParameters = new BasicHttpParams();
int connectionTimeout = 1000*12;
int socketTimeout = 1000*13;
HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout);
HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout);
// Create a new HttpClient and Post Header
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost("URL");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
try {
// Add your data
List<NameValuePair> signinDetails = new ArrayList<NameValuePair>();
signinDetails.add(new BasicNameValuePair("name", uname));
signinDetails.add(new BasicNameValuePair("pwd", pwd));
httpPost.setEntity(new UrlEncodedFormEntity(signinDetails));
// Execute HTTP Post Request
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.v("Post Status", "Code: "+ httpResponse.getStatusLine().getStatusCode());
responseCode = httpResponse.getStatusLine().getStatusCode();
Log.e("responseCode", String.valueOf("response code"+responseCode));
HttpEntity entity = httpResponse.getEntity();
Log.e("entity", String.valueOf(entity));
if (entity != null) {
if (entity != null) {
String responseBody = EntityUtils.toString(entity);
JSONTokener jsonTokener = new JSONTokener(responseBody);
jsonResponse = new JSONObject(jsonTokener);
JSONObject response = jsonResponse.getJSONObject("response");
// Getting String inside response object
String status = response.getString("status");
String message = response.getString("message");
}
} // if (entity != null) end
}
catch (SocketException seExp)
{
}
catch (ConnectTimeoutException cteExp)
{
// TODO Auto-generated catch block
}
catch (ClientProtocolException cpeExp) {
// TODO Auto-generated catch block
}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception allExp) {
// TODO Auto-generated catch block
}
return jsonResponse;
}
public class RequestLogInFromServer extends AsyncTask<Object, Object, Object>
{
private ProgressDialog progressDialog;
@Override
protected Object doInBackground(Object... params)
{
try {
JSONObject subscriptionResponse = CommonJsonParser.responseForSignin(uname, pwd).getJSONObject("response");
if (!(subscriptionResponse.equals(null))||!(subscriptionResponse.equals(""))) {
}
}
catch (NullPointerException e) {
// TODO Auto-generated catch block
}
catch (JSONException e) {
// TODO Auto-generated catch block
}
catch (Exception e) {
// TODO Auto-generated catch block
}
return null;
}
@Override
protected void onPostExecute(Object result)
{
if(progressDialog!=null){
progressDialog.dismiss();
}
super.onPostExecute(result);
}
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(SignInActivity.this, "", "Please wait");
super.onPreExecute();
}
}
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}