struts2+json+android开发整合解析终结

来源:互联网 发布:sql server视图 编辑:程序博客网 时间:2024/05/22 13:55
   上节课程我们重点介绍了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