原創:struts2+json+android開發整合解析終結

Red88Army發表於2020-04-06

上節課程我們重點介紹了struts2+json+android伺服器段的開發,那這節課程我們就重點介紹在android客戶端是怎麼解析json集合|實體物件的方式
1、首先在這裡我們新建一個android2.2的專案,新建完畢後因為此專案要進行網路訪問操作,所以第一步應該在androidMainifest.xml檔案中新增網路訪問許可權程式碼如下:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

2、然後建立業務bean及service對應的類程式碼如下:

業務Bean與上節課程中的業務一致。

Servcie層:
介面:
package cn.redarmy.service;

import java.util.List;

import cn.redarmy.domain.Good;

public interface GoodService {

// 獲取最新的商品資訊
public abstract List<Good> findAll();

// 獲取最新的單個商品的詳細資訊
public abstract Good findById();

}

Service介面的實現類:在這裡我們首先完成對商品的詳細資訊的解析:
package cn.redarmy.service.Impl;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

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 cn.redarmy.domain.Good;
import cn.redarmy.service.GoodService;

public class GoodServiceImpl implements GoodService {

// 獲取最新的商品資訊
/* (non-Javadoc)
* @see cn.redarmy.service.Impl.GoodService#findAll()
*/
@Override
public List<Good> findAll() {
// 建立請求HttpClient客戶端
HttpClient httpClient = new DefaultHttpClient();
// 建立請求的url
String url = "http://192.168.4.32:8080/shop/csdn/listNewsGoods.action";
try {
// 建立請求的物件
HttpGet get = new HttpGet(new URI(url));
// 傳送get請求
HttpResponse httpResponse = httpClient.execute(get);
// 如果服務成功返回響應
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
// 獲取伺服器響應的json字串
String json = EntityUtils.toString(entity);
return parseArrayJosn(json);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

//解析json陣列物件
private List<Good> parseArrayJosn(String json) {
List<Good> goods = new ArrayList<Good>();
try {
JSONArray array = new JSONObject(json).getJSONArray("goods");
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
Good good = new Good(obj.getInt("id"), obj.getString("name"),
(float) obj.getDouble("price"));
goods.add(good);
}
} catch (JSONException e) {
e.printStackTrace();
}
return goods;
}

// 獲取最新的單個商品的詳細資訊
/* (non-Javadoc)
* @see cn.redarmy.service.Impl.GoodService#findById()
*/
@Override
public Good findById() {
// 建立請求HttpClient客戶端
HttpClient httpClient = new DefaultHttpClient();
// 建立請求的url
String url = "http://192.168.4.32:8080/shop/csdn/findGood.action";
try {
// 建立請求的物件
HttpGet get = new HttpGet(new URI(url));
// 傳送get請求
HttpResponse httpResponse = httpClient.execute(get);
// 如果服務成功返回響應
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
// 獲取伺服器響應的json字串
String json = EntityUtils.toString(entity);
return parseObjJosn(json);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

//解析json的單個物件
private Good parseObjJosn(String json) {
JSONObject obj = null;
try {
obj = new JSONObject(json).getJSONObject("good");
Good good = new Good(obj.getInt("id"), obj.getString("name"),
(float) obj.getDouble("price"));
return good;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
建立用於顯示商品資訊的listView及對應的元件
建立good.xml檔案
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="horizontal">
<TextView android:layout_height="wrap_content" android:text="TextView" android:id="@+id/name" android:layout_width="200dip"></TextView>
<TextView android:layout_height="wrap_content" android:text="TextView" android:id="@+id/price" android:layout_width="match_parent"></TextView>

</LinearLayout>


在main.xml檔案中新增listView元件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/goods"></ListView>
</LinearLayout>

最後完成GoodActivity的編寫程式碼如下:
package cn.redarmy.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import cn.redarmy.domain.Good;
import cn.redarmy.service.GoodService;
import cn.redarmy.service.Impl.GoodServiceImpl;

public class GoodActivity extends Activity {

private GoodService goodService = new GoodServiceImpl();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//解析集合
/* try {
List<Good> goods = goodService.findAll();
ListView listView = (ListView) this.findViewById(R.id.goods);
List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
for (Good good : goods) {
HashMap<String, Object> item = new HashMap<String, Object>();
item.put("name", good.getName());
item.put("price", getResources().getString(R.string.price)+good.getPrice());
item.put("id", good.getId());
data.add(item);
}
SimpleAdapter adapter = new SimpleAdapter(this, data,
R.layout.good, new String[] { "name", "price" },
new int[] { R.id.name, R.id.price });

listView.setAdapter(adapter);
} catch (Exception e) {
Log.v("error", "網路連線失敗");
e.printStackTrace();
}*/
//解析單個物件
try {
Good good = goodService.findById();
ListView listView = (ListView) this.findViewById(R.id.goods);
List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();

HashMap<String, Object> item = new HashMap<String, Object>();
item.put("name", good.getName());
item.put("price", getResources().getString(R.string.price)+good.getPrice());
item.put("id", good.getId());
data.add(item);

SimpleAdapter adapter = new SimpleAdapter(this, data,
R.layout.good, new String[] { "name", "price" },
new int[] { R.id.name, R.id.price });

listView.setAdapter(adapter);
} catch (Exception e) {
Log.v("error", "網路連線失敗");
e.printStackTrace();
}
}
}

通過以上方式就能實現struts2+android+json的開發了,希望你所有收穫

以上內容歸redarmychen版權所有,如想轉載請附帶出處,如有疑問請發郵件至redarmy.chen@gmail.com

相關文章