簡介
這裏主要介紹Android生成一個Json格式的字符串,客戶端通過網絡獲取服務器端生成的Json字符串進行解析,根據解析出來的Url去網絡獲取圖片並顯示在ListView中。最終實現效果如下
Json字符串爲
{
"result": 1,
"list": [
{
"name": "nate",
"age": 12,
"url": "http://imgst-dl.meilishuo.net/pic/_o/84/a4/a30be77c4ca62cd87156da202faf_1440_900.jpg",
"schoolInfo": [
{
"schoolName": "清華"
},
{
"schoolName": "北大"
}
]
},
{
"name": "cat",
"age": 22,
"url": "http://s2.nuomi.bdimg.com/upload/deal/2014/1/V_L/623682-1391756281052.jpg",
"schoolInfo": [
{
"schoolName": "新東方"
},
{
"schoolName": "藍翔"
}
]
},
{
"name": "cat",
"age": 22,
"url": "http://www.33lc.com/article/UploadPic/2012-8/201282413335761587.jpg",
"schoolInfo": [
{
"schoolName": "武當"
},
{
"schoolName": "峨眉"
}
]
},
{
"name": "jack",
"age": 12,
"url": "http://imgst-dl.meilishuo.net/pic/_o/84/a4/a30be77c4ca62cd87156da202faf_1440_900.jpg",
"schoolInfo": [
{
"schoolName": "清華"
},
{
"schoolName": "北大"
}
]
}
]
}
服務器端生成Json字符串
生成Json字符串,首先需要建立幾個類public class Result {
private int result;
private List<Person> list;
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public List<Person> getList() {
return list;
}
public void setList(List<Person> list) {
this.list = list;
}
}
Person.javapublic class Person {
private String name;
private int age;
private String url;
private List<SchoolInfo> schoolInfo = new ArrayList<SchoolInfo>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public List<SchoolInfo> getSchoolInfo() {
return schoolInfo;
}
public void setSchoolInfo(List<SchoolInfo> schoolInfo) {
this.schoolInfo = schoolInfo;
}
}
SchoolInfo.javapublic class SchoolInfo {
private String schoolName;
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
}
JsonServlet.java 生成Json字符串(這裏需要用到Gson.jar包)/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
Result result = new Result();
result.setResult(1);
List<Person> lists = new ArrayList<Person>();
result.setList(lists);
Person person1 = new Person();
person1.setName("nate");
person1.setAge(12);
person1.setUrl("http://imgst-dl.meilishuo.net/pic/_o/84/a4/a30be77c4ca62cd87156da202faf_1440_900.jpg");
List<SchoolInfo> schoolInfos = new ArrayList<SchoolInfo>();
SchoolInfo schoolInfo1 = new SchoolInfo();
schoolInfo1.setSchoolName("清華");
SchoolInfo schoolInfo2 = new SchoolInfo();
schoolInfo2.setSchoolName("北大");
schoolInfos.add(schoolInfo1);
schoolInfos.add(schoolInfo2);
person1.setSchoolInfo(schoolInfos);
lists.add(person1);
Person person2 = new Person();
person2.setName("cat");
person2.setAge(22);
person2.setUrl("http://s2.nuomi.bdimg.com/upload/deal/2014/1/V_L/623682-1391756281052.jpg");
List<SchoolInfo> schoolInfos2 = new ArrayList<SchoolInfo>();
SchoolInfo schoolInfo3 = new SchoolInfo();
schoolInfo3.setSchoolName("新東方");
SchoolInfo schoolInfo4 = new SchoolInfo();
schoolInfo4.setSchoolName("藍翔");
schoolInfos2.add(schoolInfo3);
schoolInfos2.add(schoolInfo4);
person2.setSchoolInfo(schoolInfos2);
lists.add(person2);
Person person3 = new Person();
person3.setName("cat");
person3.setAge(22);
person3.setUrl("http://www.33lc.com/article/UploadPic/2012-8/201282413335761587.jpg");
List<SchoolInfo> schoolInfos3 = new ArrayList<SchoolInfo>();
SchoolInfo schoolInfo5 = new SchoolInfo();
schoolInfo5.setSchoolName("武當");
SchoolInfo schoolInfo6 = new SchoolInfo();
schoolInfo6.setSchoolName("峨眉");
schoolInfos3.add(schoolInfo5);
schoolInfos3.add(schoolInfo6);
person3.setSchoolInfo(schoolInfos3);
lists.add(person3);
Person person4 = new Person();
person4.setName("jack");
person4.setAge(12);
person4.setUrl("http://imgst-dl.meilishuo.net/pic/_o/84/a4/a30be77c4ca62cd87156da202faf_1440_900.jpg");
List<SchoolInfo> schoolInfos4 = new ArrayList<SchoolInfo>();
SchoolInfo schoolInfo7 = new SchoolInfo();
schoolInfo7.setSchoolName("清華");
SchoolInfo schoolInfo8 = new SchoolInfo();
schoolInfo8.setSchoolName("北大");
schoolInfos4.add(schoolInfo7);
schoolInfos4.add(schoolInfo8);
person4.setSchoolInfo(schoolInfos);
lists.add(person4);
Gson gson = new Gson();
System.out.println(gson.toJson(result));
//返回Json給客戶端
out.print(gson.toJson(result));
}
客戶端解析Json字符串並下載圖片<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/imageview"
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_alignParentLeft="true"/>
<LinearLayout
android:layout_toRightOf="@+id/imageview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/age"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/school1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"/>
<TextView
android:id="@+id/school2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"/>
</LinearLayout>
</RelativeLayout>
ListView 的適配器類 JsonAdapter.java類public class JsonAdapter extends BaseAdapter{
private List<Person> list;
private Context mContext;
private LayoutInflater inflater;
private Handler handler = new Handler();
public JsonAdapter(Context context){
this.mContext = context;
inflater = LayoutInflater.from(mContext);
}
public void setData(List<Person> data){
this.list = data;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = null;
if(convertView == null){
convertView = inflater.inflate(R.layout.item, null);
holder = new Holder(convertView);
convertView.setTag(holder);
}else{
holder = (Holder)convertView.getTag();
}
Person person = list.get(position);
holder.name.setText(person.getName());
holder.age.setText(""+person.getAge());//這裏age是int型,如果不改成string的話會報找不到資源錯誤
List<SchoolInfo> schoolInfos = person.getSchoolInfo();
SchoolInfo schoolInfo1 = schoolInfos.get(0);
SchoolInfo schoolInfo2 = schoolInfos.get(1);
holder.school1.setText(schoolInfo1.getSchoolName());
holder.school2.setText(schoolInfo2.getSchoolName());
//通過獲取到的url去網絡獲取圖片並使用handler顯示在界面上
new HttpImages(holder.imageView, handler, person.getUrl()).start();
return convertView;
}
class Holder{
private ImageView imageView;
private TextView name;
private TextView age;
private TextView school1;
private TextView school2;
public Holder(View view){
imageView = (ImageView)view.findViewById(R.id.imageview);
name = (TextView)view.findViewById(R.id.name);
age = (TextView)view.findViewById(R.id.age);
school1 = (TextView)view.findViewById(R.id.school1);
school2 = (TextView)view.findViewById(R.id.school2);
}
}
}
訪問網絡獲取JSon並解析Json類 JsonHttpJson.javapublic class JsonHttpJson extends Thread{
private String url;
private ListView listView;
private Context context;
private JsonAdapter adapter;
private Handler handler;
public JsonHttpJson(String url,Context context,ListView listView,JsonAdapter adapter,Handler handler){
this.url = url;
this.context = context;
this.listView = listView;
this.adapter = adapter;
this.handler = handler;
}
@Override
public void run() {
URL httpUrl = null;
try {
//從服務器獲取Json字符串
httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setReadTimeout(3000);
conn.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer buffer = new StringBuffer();
String str;
while((str= reader.readLine())!= null){
buffer.append(str);
}
//解析獲取到的Json字符串,返回一個Person的集合
final List<Person> data = parseJson(buffer.toString());
handler.post(new Runnable() {
@Override
public void run() {
//設置數據源,設置適配器
adapter.setData(data);
listView.setAdapter(adapter);
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//解析JSon
private List<Person> parseJson(String json){
try {
JSONObject object = new JSONObject(json);
int result = object.getInt("result");
if(result == 1){
//獲取一個json對象數組
JSONArray personArray = object.getJSONArray("list");
List<Person> persons = new ArrayList<Person>();
//遍歷數組,繼續解析
for(int i = 0;i<personArray.length();i++){
Person personM = new Person();
JSONObject person = personArray.getJSONObject(i);
String name = person.getString("name");
int age = person.getInt("age");
String url = person.getString("url");
personM.setAge(age);
personM.setName(name);
personM.setUrl(url);
//schoolInfos爲一個數組,繼續進行for循環解析
JSONArray schoolInfos = person.getJSONArray("schoolInfo");
List<SchoolInfo> infos = new ArrayList<SchoolInfo>();
for(int j = 0 ;j<schoolInfos.length();j++){
SchoolInfo info = new SchoolInfo();
JSONObject school = schoolInfos.getJSONObject(j);
String schoolName = school.getString("schoolName");
info.setSchoolName(schoolName);
infos.add(info);
}
personM.setSchoolInfo(infos);
//把解析出的對象加入到list中
persons.add(personM);
}
return persons;
}else{
Toast.makeText(context, "json error", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
從網絡獲取圖片並顯示在ImageView上的類 HttpImages.javapublic class HttpImages extends Thread{
private ImageView imageView;
private Handler handler;
private String url;
public HttpImages(ImageView imageView,Handler handler,String url){
this.imageView = imageView;
this.handler = handler;
this.url = url;
}
@Override
public void run() {
URL httpUrl;
try {
httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setReadTimeout(3000);
conn.setRequestMethod("GET");
//獲取輸入流
InputStream in = conn.getInputStream();
//解析輸入流獲取圖片
final Bitmap bitmap = BitmapFactory.decodeStream(in);
//使用handler 更新界面
handler.post(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
主類,調用類:MainActivity.javapublic class MainActivity extends Activity {
private ListView listView;
private JsonAdapter adapter;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listview);
adapter = new JsonAdapter(this);
String url = "http://192.168.199.126:8080/Server/JsonServlet";
new JsonHttpJson(url, this,listView,adapter,handler).start();
}
}