如何在Java(Android Studio)中处理JSON
我是android新手,正在开发android应用程序,我想从URL获取JSON数据: 我有以下代码:如何在Java(Android Studio)中处理JSON,java,android,json,android-studio,Java,Android,Json,Android Studio,我是android新手,正在开发android应用程序,我想从URL获取JSON数据: 我有以下代码: import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.method
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class SingleContactActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.article);
String url = "http://ana.fm/api/article/256281468161349/";
TextView title = (TextView) findViewById(R.id.single_article_title);
TextView desc = (TextView) findViewById(R.id.single_article_desc);
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpGet myConnection = new HttpGet(url);
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONObject parent_obj = new JSONObject(str);
JSONArray jArray= parent_obj.getJSONArray("article");
JSONObject json = jArray.getJSONObject(0);
title.setText(json.getString("title"));
desc.setText(json.getString("description"));
} catch ( JSONException e) {
e.printStackTrace();
}
}
}
这是article.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Article Cover Photo -->
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/single_article_cover_photo"
android:layout_gravity="center_horizontal" />
<!-- Article Title -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/single_article_title"
android:layout_gravity="center_horizontal"
android:textColor="#acacac" />
<!-- Article Description -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/single_article_desc"
android:layout_gravity="center_horizontal" />
</LinearLayout>
我已经在AndroidManifest.xml中设置了internet权限:
<uses-permission android:name="android.permission.INTERNET" />
但当我运行模拟器时,我得到:
无效的
空的
我在代码中找不到任何错误
我用这个代码得到了它:
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.TextView;
import java.io.InputStream;
public class SingleContactActivity extends Activity {
public static String myArticleUrl = "http://ana.fm/api/article/256281468161349/";
TextView title;
TextView desc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.article);
title = (TextView) findViewById(R.id.single_article_title);
desc = (TextView) findViewById(R.id.single_article_desc);
new LoadAllArticles().execute();
}
// LOADING THE ARTICLE CONTENTS IN THE BACKGROUND
class LoadAllArticles extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(SingleContactActivity.this);
InputStream inputStream = null;
String result = "";
HttpResponse httpResponse;
HttpEntity httpEntity;
protected void onPreExecute() {
progressDialog.setMessage("Downloading article...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
LoadAllArticles.this.cancel(true);
}
});
}
@Override
protected Void doInBackground(String... params) {
String url_select = myArticleUrl;
// Set up HTTP Get
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url_select);
try {
httpResponse = httpClient.execute(httpGet);
result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONObject parent_obj = new JSONObject(result);
JSONArray jArray= parent_obj.getJSONArray("article");
JSONObject json = jArray.getJSONObject(0);
title.setText(json.getString("title"));
desc.setText(json.getString("description"));
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
}
}
}
import java.io.IOException;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.util.EntityUtils;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.ProgressDialog;
导入android.content.DialogInterface;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.app.Activity;
导入android.util.Log;
导入android.widget.TextView;
导入java.io.InputStream;
公共类SingleContactActivity扩展了活动{
公共静态字符串myArticleUrl=”http://ana.fm/api/article/256281468161349/";
文本视图标题;
文本视图描述;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.article);
title=(TextView)findViewById(R.id.single\u article\u title);
desc=(TextView)findViewById(R.id.single\u article\u desc);
新建LoadAllArticles().execute();
}
//在后台加载文章内容
类LoadAllArticles扩展了AsyncTask{
private ProgressDialog ProgressDialog=新建ProgressDialog(SingleContactActivity.this);
InputStream InputStream=null;
字符串结果=”;
HttpResponse HttpResponse;
HttpEntity HttpEntity;
受保护的void onPreExecute(){
setMessage(“下载文章…”);
progressDialog.show();
progressDialog.setOnCancelListener(新的DialogInterface.OnCancelListener(){
public void onCancel(对话框接口arg0){
LoadAllArticles.this.cancel(true);
}
});
}
@凌驾
受保护的Void doInBackground(字符串…参数){
字符串url\u select=myArticleUrl;
//设置HTTP Get
HttpClient HttpClient=新的DefaultHttpClient();
HttpGet HttpGet=新的HttpGet(url\u选择);
试一试{
httpResponse=httpClient.execute(httpGet);
结果=EntityUtils.toString(httpResponse.getEntity(),“UTF-8”);
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
返回null;
}
受保护的void onPostExecute(void v){
//解析JSON数据
试一试{
JSONObject父对象=新JSONObject(结果);
JSONArray jArray=父对象getJSONArray(“文章”);
JSONObject json=jArray.getJSONObject(0);
title.setText(json.getString(“title”);
desc.setText(json.getString(“description”);
此.progressDialog.discouse()文件;
}捕获(JSONException e){
Log.e(“JSONException”,“Error:+e.toString());
}//catch(JSONException e)
}
}
}
但是现在我需要处理HTML标记,有人知道我如何处理JSON中的HTML标记吗?编辑:好的,我终于设法进入我的工作PC,所以我纠正了所有错误,现在可以工作了:
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.TextView;
import java.io.InputStream;
import java.util.ArrayList;
public class SingleContactActivity extends Activity {
String myArticleUrl = "http://ana.fm/api/article/256281468161349/";
TextView txtTitle;
TextView txtDesc;
JSONParser jParser = new JSONParser();
JSONArray articles = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.article);
txtTitle = (TextView) findViewById(R.id.single_article_title);
txtDesc = (TextView) findViewById(R.id.single_article_desc);
new LoadAllArticles().execute();
}
// LOADING ALL ARTICLES IN THE BACKGROUND
class LoadAllArticles extends AsyncTask<String, String, String> {
private ProgressDialog progressDialog = new ProgressDialog(SingleContactActivity.this);
InputStream inputStream = null;
String result = "";
String title = "";
String description = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading articles...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
LoadAllArticles.this.cancel(true);
}
});
}
@Override
protected String doInBackground(String... params) {
String url_select = myArticleUrl;
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
JSONObject json = jParser.makeHttpRequest(url_select,
"GET", param); // Change "GET" to "POST" if you want the POST method
articles = json.getJSONArray("article");
JSONObject jsonObj = articles.getJSONObject(0);
title = jsonObj.getString("title");
description = jsonObj.getString("description");
}
catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
}
catch (JSONException e5) {
Log.e("JSONException", e5.toString());
e5.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
try {
String newTitle = Html.fromHtml(title).toString();
txtTitle.setText(newTitle);
String newDesc = Html.fromHtml(description).toString();
txtDesc.setText(newDesc);
progressDialog.dismiss();
} catch (Exception e) {
Log.e("JSONException", "Error: " + e.toString());
}
}
}
}
试试这个,它对我有效,我可以看到一堆阿拉伯语文本…编辑:好的,我终于设法进入我的工作电脑,所以我纠正了所有错误,现在可以了:
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.TextView;
import java.io.InputStream;
import java.util.ArrayList;
public class SingleContactActivity extends Activity {
String myArticleUrl = "http://ana.fm/api/article/256281468161349/";
TextView txtTitle;
TextView txtDesc;
JSONParser jParser = new JSONParser();
JSONArray articles = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.article);
txtTitle = (TextView) findViewById(R.id.single_article_title);
txtDesc = (TextView) findViewById(R.id.single_article_desc);
new LoadAllArticles().execute();
}
// LOADING ALL ARTICLES IN THE BACKGROUND
class LoadAllArticles extends AsyncTask<String, String, String> {
private ProgressDialog progressDialog = new ProgressDialog(SingleContactActivity.this);
InputStream inputStream = null;
String result = "";
String title = "";
String description = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading articles...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
LoadAllArticles.this.cancel(true);
}
});
}
@Override
protected String doInBackground(String... params) {
String url_select = myArticleUrl;
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
JSONObject json = jParser.makeHttpRequest(url_select,
"GET", param); // Change "GET" to "POST" if you want the POST method
articles = json.getJSONArray("article");
JSONObject jsonObj = articles.getJSONObject(0);
title = jsonObj.getString("title");
description = jsonObj.getString("description");
}
catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
}
catch (JSONException e5) {
Log.e("JSONException", e5.toString());
e5.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
try {
String newTitle = Html.fromHtml(title).toString();
txtTitle.setText(newTitle);
String newDesc = Html.fromHtml(description).toString();
txtDesc.setText(newDesc);
progressDialog.dismiss();
} catch (Exception e) {
Log.e("JSONException", "Error: " + e.toString());
}
}
}
}
试试这个,它对我有效,我可以看到一堆阿拉伯语文本…编辑:好的,我终于设法进入我的工作电脑,所以我纠正了所有错误,现在可以了:
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.TextView;
import java.io.InputStream;
import java.util.ArrayList;
public class SingleContactActivity extends Activity {
String myArticleUrl = "http://ana.fm/api/article/256281468161349/";
TextView txtTitle;
TextView txtDesc;
JSONParser jParser = new JSONParser();
JSONArray articles = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.article);
txtTitle = (TextView) findViewById(R.id.single_article_title);
txtDesc = (TextView) findViewById(R.id.single_article_desc);
new LoadAllArticles().execute();
}
// LOADING ALL ARTICLES IN THE BACKGROUND
class LoadAllArticles extends AsyncTask<String, String, String> {
private ProgressDialog progressDialog = new ProgressDialog(SingleContactActivity.this);
InputStream inputStream = null;
String result = "";
String title = "";
String description = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading articles...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
LoadAllArticles.this.cancel(true);
}
});
}
@Override
protected String doInBackground(String... params) {
String url_select = myArticleUrl;
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
JSONObject json = jParser.makeHttpRequest(url_select,
"GET", param); // Change "GET" to "POST" if you want the POST method
articles = json.getJSONArray("article");
JSONObject jsonObj = articles.getJSONObject(0);
title = jsonObj.getString("title");
description = jsonObj.getString("description");
}
catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
}
catch (JSONException e5) {
Log.e("JSONException", e5.toString());
e5.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
try {
String newTitle = Html.fromHtml(title).toString();
txtTitle.setText(newTitle);
String newDesc = Html.fromHtml(description).toString();
txtDesc.setText(newDesc);
progressDialog.dismiss();
} catch (Exception e) {
Log.e("JSONException", "Error: " + e.toString());
}
}
}
}
试试这个,它对我有效,我可以看到一堆阿拉伯语文本…编辑:好的,我终于设法进入我的工作电脑,所以我纠正了所有错误,现在可以了:
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.TextView;
import java.io.InputStream;
import java.util.ArrayList;
public class SingleContactActivity extends Activity {
String myArticleUrl = "http://ana.fm/api/article/256281468161349/";
TextView txtTitle;
TextView txtDesc;
JSONParser jParser = new JSONParser();
JSONArray articles = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.article);
txtTitle = (TextView) findViewById(R.id.single_article_title);
txtDesc = (TextView) findViewById(R.id.single_article_desc);
new LoadAllArticles().execute();
}
// LOADING ALL ARTICLES IN THE BACKGROUND
class LoadAllArticles extends AsyncTask<String, String, String> {
private ProgressDialog progressDialog = new ProgressDialog(SingleContactActivity.this);
InputStream inputStream = null;
String result = "";
String title = "";
String description = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading articles...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
LoadAllArticles.this.cancel(true);
}
});
}
@Override
protected String doInBackground(String... params) {
String url_select = myArticleUrl;
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
JSONObject json = jParser.makeHttpRequest(url_select,
"GET", param); // Change "GET" to "POST" if you want the POST method
articles = json.getJSONArray("article");
JSONObject jsonObj = articles.getJSONObject(0);
title = jsonObj.getString("title");
description = jsonObj.getString("description");
}
catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
}
catch (JSONException e5) {
Log.e("JSONException", e5.toString());
e5.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
try {
String newTitle = Html.fromHtml(title).toString();
txtTitle.setText(newTitle);
String newDesc = Html.fromHtml(description).toString();
txtDesc.setText(newDesc);
progressDialog.dismiss();
} catch (Exception e) {
Log.e("JSONException", "Error: " + e.toString());
}
}
}
}
试试这个,它对我有用,我可以看到一堆阿拉伯文本…而不是肛门解析,你可以使用
. 您将得到您的发布是java对象。您可以使用
. 您将得到您的发布是java对象。您可以使用
. 您将得到您的发布是java对象。您可以使用
. 您将得到您的发布是java对象。首先,不要在主线程中执行HTTP请求。您受到NetworkOnMainThread异常的影响。将用于获取JSON数据的代码移动到asynctask。我如何才能做到这一点@ZouZouIt在文档中:-您还可以使用更简单的方法:有几个库专门用于异步网络,例如volley或首先,不要在主线程中执行HTTP请求。您受到NetworkOnMainThread异常的影响。将用于获取JSON数据的代码移动到asynctask。我如何才能做到这一点@ZouZouIt在文档中:-您还可以使用更简单的方法:有几个库专门用于异步网络,例如volley或首先,不要在主线程中执行HTTP请求。您受到NetworkOnMainThread异常的影响。将用于获取JSON数据的代码移动到asynctask。我如何才能做到这一点@ZouZouIt在文档中:-您还可以使用一种更简单的方法:有几个库专门为异步网络而设计,比如volley或首先,不做HTTP请求