安卓使用FastJson解析Json資料並展示到ListView中
阿新 • • 發佈:2019-01-31
先上效果圖:
今天繼續講安卓端解析Json資料,資料存放在tomcat伺服器,伺服器端採用SSH框架編碼完成,由安卓端通過http的GET請求獲取到json物件陣列,之後就是解析啦,解析完將所有資料存放在實體類中,接下來就是將資料顯示在ListView上面了。伺服器的搭建比較簡單了,其中在action中處理安卓端的get請求,將資料以位元組流的方式返回給安卓端.
服務端action程式碼:
//獲取資料,通過json
public String getDataByJson(){
try {
request.setCharacterEncoding ("UTF-8");
response.setContentType("text/html;charset:UTF-8");
response.setCharacterEncoding("UTF-8");
List<Person> persons=personBiz.getXmlData();
for (Person person : persons) {
System.out.println(person);
}
request.setAttribute ("persons", persons);
//Json傳輸資料至頁面
JSONArray jsonArray=new JSONArray();
jsonArray=JSONArray.fromObject(persons);
String str=jsonArray.toString();
response.setCharacterEncoding("UTF-8");
PrintWriter pw=response.getWriter ();
pw.write(str);
pw.close();
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
dao層介面程式碼:
//查詢所有xml資料
public List<Person> getXmlData();
struts.xml中配置action:
<action name="getDataByJson" class="personAction" method="getDataByJson">
<result name="success">/list.jsp</result>
</action>
服務端頁面請求程式碼:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<a href="getDataByJson.action">解析Json資料</a>
</center>
</body>
</html>
伺服器端頁面返回資料頁面:
<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8"%>${persons}
執行結果圖:
安卓端http的GET請求獲取到物件陣列,並解析,將資料存放到實體類中:
package com.example.android_parsexml;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2017/2/25.
*/
public class TwoActivity extends AppCompatActivity {
private ListView lv_main_list2;
private List<Person> personList = new ArrayList<Person>();
private ProgressDialog progressDialog;
private MyAdapter myAdapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
//獲取listview
lv_main_list2 = (ListView) findViewById(R.id.lv_main_list2);
//例項化進度條對話方塊
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("親,正在玩命載入中哦!");
//例項化介面卡
myAdapter = new MyAdapter();
//設定介面卡
lv_main_list2.setAdapter(myAdapter);
}
//自己寫個介面卡類
class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return personList.size();
}
@Override
public Object getItem(int i) {
return personList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
LinearLayout layout = new LinearLayout(TwoActivity.this);
layout.setOrientation(LinearLayout.HORIZONTAL);
TextView textViewPage = new TextView(TwoActivity.this);
textViewPage.setText(personList.get(i).getPage() + "\t\t\t\t" + " ");
TextView textViewPname = new TextView(TwoActivity.this);
textViewPname.setText(personList.get(i).getPname() + "\t\t\t\t");
TextView textViewPid = new TextView(TwoActivity.this);
textViewPid.setText(personList.get(i).getPid() + "\t\t\t\t");
layout.addView(textViewPid);
layout.addView(textViewPname);
layout.addView(textViewPage);
return layout;
}
}
//獲取xml資料
public void getJson(View view) {
new MyTask().execute();
}
//通過非同步任務類獲取資料
class MyTask extends AsyncTask {
private Person person;
//準備執行
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
@Override
protected Object doInBackground(Object[] params) {
//獲取網路路徑
String path = "http://193.168.4.71:8080/S2SH/getDataByJson.action";
//例項化URL
try {
URL url = new URL(path);
//獲取連線物件
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//設定請求方式
httpURLConnection.setRequestMethod("GET");
//設定連線超時
httpURLConnection.setConnectTimeout(5000);
//獲取響應碼
int code = httpURLConnection.getResponseCode();
if (code == 200) {
//響應成功,獲取伺服器返回過來的資料
InputStream is = httpURLConnection.getInputStream();
//測試資料
StringBuffer stringBuffer = new StringBuffer();
String str = null;
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((str = br.readLine()) != null) {
stringBuffer.append(str);
}
//03.使用fastJson解析Json、
List<Person> persons = JSON.parseArray(stringBuffer.toString(), Person.class);
for (Person pp : persons) {
person = new Person();
int pid = pp.getPid();
String pname = pp.getPname();
int page = pp.getPage();
person.setPid(pid);
person.setPname(pname);
person.setPage(page);
//將結果新增到物件集合中
personList.add(person);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
//通知介面卡發生改變
myAdapter.notifyDataSetChanged();
//取消進度條對話方塊
progressDialog.cancel();
}
}
}
layout.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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="獲取Json資料"
android:onClick="getJson"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:id="@+id/lv_main_list2"
></ListView>
</LinearLayout>
實體類程式碼;
package com.example.android_parsexml;
public class Person {
private int pid;
private String pname;
private int page;
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public Person() {
super();
}
public Person(String pname, int page) {
super();
this.pname = pname;
this.page = page;
}
@Override
public String toString() {
return "Person [pid=" + pid + ", pname=" + pname + ", page=" + page + "]";
}
}
mainfests 新增許可權:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
注:獲取網路路徑時,地址為當前網路地址。還有聯網許可權別忘啦!