Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android數據轉化為Json形式給客戶端及客戶端使用json數據

Android數據轉化為Json形式給客戶端及客戶端使用json數據

編輯:關於Android編程

(1)首先創建生成原始數據的service,VideoNewsServiceBean,這是一個接口的實現類,接口的功能如下:

public interface VideoNewsService {
    /**
     * 獲取最新的視頻資訊
     * @return
     */
    public List getLastNews();

}

News類

public class News {
    private Integer id;
    private String title;
    private Integer timelength;

    public News(Integer id, String title, Integer timelength) {
        this.id = id;
        this.title = title;
        this.timelength = timelength;
    }
    //get/set方法
}

接口的實現類:生成一些假數據

public class VideoNewsServiceBean implements VideoNewsService {

    public List getLastNews(){
        List newes = new ArrayList();
        newes.add(new News(90, "喜羊羊與灰太狼全集", 78));
        newes.add(new News(10, "實拍艦載直升東海救援演習", 28));
        newes.add(new News(56, "喀麥隆VS荷蘭", 70));
        return newes;
    }
}

(2)通過servlet將數據返回給客戶端:ListServlet.java

public class ListServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private VideoNewsService service = new VideoNewsServiceBean();

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        List videos = service.getLastNews();

            // [{id:56,title:"xxxxx",timelength:90},{id:16,title:"xbbx",timelength:20}]
            StringBuilder builder = new StringBuilder();
            //對數據進行追加為json格式
            builder.append('[');
            for (News news : videos) {
                builder.append('{');
                builder.append("id:").append(news.getId()).append(',');
                builder.append("title:\"").append(news.getTitle())
                        .append("\",");
                builder.append("timelength:").append(news.getTimelength());
                builder.append("},");
            }
            //刪除最後一個多的字符
            builder.deleteCharAt(builder.length() - 1);
            builder.append(']');
            //將數據設置在request域中,進行跳轉,當客戶端請求該servlet的時候跳轉到該jsp頁面,實際請求的為jsp頁面
            request.setAttribute("json", builder.toString());
            request.getRequestDispatcher("/WEB-INF/page/jsonvideonews.jsp")
                    .forward(request, response);
    }

}

(3)當客戶端通過servlet請求的時候就經過跳轉可以返回jsp頁面數據(使用的是el表達式,因為json數據為String類型所以 contentType=”text/plain; charset=UTF-8”)

<%@ page language="java" contentType="text/plain; charset=UTF-8" pageEncoding="UTF-8"%>${json}

(4)在客戶端取出數據
同樣的第一步仍是創建一個News的類,這裡省略
創建一個獲取Json的service,VideoNewsService.java

public class VideoNewsService {
    /**
     * 獲取最新的視頻資訊
     * @return
     * @throws Exception
     */
    public static List getJSONLastNews() throws Exception{
        String path = "服務器請求servlet的地址";
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if(conn.getResponseCode() == 200){
            InputStream inStream = conn.getInputStream();
            return parseJSON(inStream);
        }
        return null;
    }
    /**
     * 解析JSON數據
     * @param inStream
     * @return
     */
    private static List parseJSON(InputStream inStream) throws Exception{
        List newses = new ArrayList();
        byte[] data = StreamTool.read(inStream);
        String json = new String(data);
        //因為數據是類似於數組的形式重復的使用JSONArray
        JSONArray array = new JSONArray(json);
        for(int i = 0 ; i < array.length() ; i++){
            JSONObject jsonObject = array.getJSONObject(i);
            News news = new News(jsonObject.getInt("id"), jsonObject.getString("title"), jsonObject.getInt("timelength"));
            newses.add(news);
        }
        return newses;
    }
}

這裡邊使用了一個工具類StreamTool.java,將輸入流轉化為byte數據返回

public class StreamTool {
    /**
     * 讀取輸入流數據
     */
    public static byte[] read(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

然後皆可以在具體的界面中進行數據的使用:(這裡為一個listview設置值)
MainActivity.java

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ListView listView = (ListView) this.findViewById(R.id.listView);
        try {
            List videos = VideoNewsService.getJSONLastNews();//需修改成你本機的Http請求路徑
            //這裡使用的List>可以將數據放入hashmap之後再放入list集合中
            List> data = new ArrayList>();
            for(News news : videos){
                HashMap item = new HashMap();
                item.put("id", news.getId());
                item.put("title", news.getTitle());
                item.put("timelength", getResources().getString(R.string.timelength)
                        + news.getTimelength()+ getResources().getString(R.string.min));
                data.add(item);
            }
            //為listview設置適配器
            SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,
                    new String[]{"title", "timelength"}, new int[]{R.id.title, R.id.timelength});
            listView.setAdapter(adapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

到此json數據的生成客客戶端使用json數據操作已經完成!

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved