Android数据转化为Json形式给客户端及客户端使用json数据

(1)首先创建生成原始数据的service,VideoNewsServiceBean,这是一个接口的实现类,接口的功能如下:

public interface VideoNewsService {
    /**
     * 获取最新的视频资讯
     * @return
     */
    public List<News> 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<News> getLastNews(){
        List<News> newes = new ArrayList<News>();
        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<News> 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<News> 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<News> parseJSON(InputStream inStream) throws Exception{
        List<News> newses = new ArrayList<News>();
        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<News> videos = VideoNewsService.getJSONLastNews();//需修改成你本机的Http请求路径
            //这里使用的List<HashMap<String, Object>>可以将数据放入hashmap之后再放入list集合中
            List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
            for(News news : videos){
                HashMap<String, Object> item = new HashMap<String, Object>();
                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数据操作已经完成!

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。