在服务器与客户端之间通信,json数据是一种常用格式,本文主要在服务器端构建数据,在客户端接收显示,并且在listview上显示出来

服务器端的构建

简单的javabean与返回结果函数与插入函数略过

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); List<MyShop> shops = JsonService.getListShop(); StringBuffer sb = new StringBuffer(); sb.append('['); for (MyShop shop : shops) { sb.append('{').append("\"name\":").append("\""+shop.getName()+"\"").append(",");
sb.append("\"detail\":").append("\""+shop.getDetail()+"\"").append(",");
sb.append("\"distance\":").append("\""+shop.getDistance()+"\"").append(",");
sb.append("\"address\":").append("\""+shop.getAddress()+"\"").append(",");
sb.append("\"popularity\":").append(shop.getPopularity());
sb.append('}').append(",");
} sb.deleteCharAt(sb.length() - 1); sb.append(']'); out.write(new String(sb)); out.flush(); out.close(); }

在浏览器中直接输入访问http://localhost:8080/AppServer/JsonServlet

可得

可以在服务器端直接查看json数据

客户端接收与解析json数据

public class JsonParse {

    /**

     * 解析Json数据

     *

     * @param urlPath

     * @return mlists

     * @throws Exception

     */

    public static List<MyShop> getListShop(String urlPath) throws Exception {

            List<MyShop> mlists = new ArrayList<MyShop>();

            byte[] data = readParse(urlPath);

            JSONArray array = new JSONArray(new String(data));

            for (int i = 0; i < array.length(); i++) {

                    JSONObject item = array.getJSONObject(i);

                    String name = item.getString("name");
String detail = item.getString("detail");
String distance = item.getString("distance"); String popularity = item.getString("popularity"); String address = item.getString("address"); mlists.add(new MyShop(name, detail, distance,address,popularity)); } return mlists; } /** * 从指定的url中获取字节数组 * * @param urlPath * @return 字节数组 * @throws Exception */ public static byte[] readParse(String urlPath) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; URL url = new URL(urlPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); InputStream inStream = conn.getInputStream(); while ((len = inStream.read(data)) != -1) { outStream.write(data, 0, len); } inStream.close(); return outStream.toByteArray(); } }

在activity中开启子线程来接收服务器数据

new Thread(new Runnable() {

            private String tag;

            @Override
public void run() {
// TODO Auto-generated method stub
//获得新闻集合 List<MyShop> shopList = null;
try {
shopList = JsonParse.getListShop("http://192.168.247.1:8080/AppServer/JsonServlet");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i(tag, "在RUN中LIST长度为"+shopList.size());
Message msg=new Message();
if(shopList!=null)
{
msg.what=SUCCESS;
msg.obj=shopList; }else
{
msg.what=FAILED;
}
handler.sendMessage(msg);
Log.i(tag, "***********T长度为"+shopList.size()); }
}).start();

消息处理器

 //消息处理器
private Handler handler=new Handler(){ /**
* 接收消息
*/
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub String tag = null;
switch (msg.what) {
case SUCCESS: //访问成功,有数据 //绑定数据
Log.i(tag,"%%%%%%%%%%到达了消息处理器");
myshoplist=(List<MyShop>) msg.obj;
Log.i(tag, "handleMessage中数据newInfoList长度为"+myshoplist.size());
NearAdapter adapter=new NearAdapter();
Log.i(tag, "有没有到达ADAPTER"+adapter.getCount());
showList.setAdapter(adapter); break; case FAILED: //访问失败
Toast.makeText(ChooseMer.this, "当前网络崩溃了", 0).show();
break; default:
break;
} } };

配置适配器

public class NearAdapter extends BaseAdapter {

        @Override
public int getCount() {
// TODO Auto-generated method stub
return myshoplist.size();
} @Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
} @Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
} @Override
public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) {
LayoutInflater inflater = LayoutInflater
.from(ChooseMer.this);
convertView = inflater.inflate(R.layout.nearby_list_item, null);
init(convertView,position);
} return convertView;
} public void init(View convertView,int position) {
hold.name = (TextView) convertView
.findViewById(R.id.nearby_item_name);
MyShop shop=myshoplist.get(position);
hold.name.setText(shop.getName());
hold.local = (TextView) convertView
.findViewById(R.id.nearby_item_local);
hold.local.setText(shop.getDetail());
hold.dis1 = (TextView) convertView
.findViewById(R.id.nearby_item_dis1);
hold.dis1.setText(shop.getDistance());
hold.dis2 = (TextView) convertView
.findViewById(R.id.nearby_item_dis2);
hold.dis2.setText(shop.getAddress());
hold.dis3 = (TextView) convertView
.findViewById(R.id.nearby_item_dis3);
hold.dis3.setText(shop.getPopularity());
}
}

配置完成,效果如下

Android客户端与服务器之间传递json数据的更多相关文章

  1. 使用HttpURLConnection实现在android客户端和服务器之间传递对象

    一般情况下,客户端和服务端的数据交互都是使用json和XML,相比于XML,json更加轻量级,并且省流量,但是,无论我们用json还是用xml,都需要我们先将数据封装成json字符串或者是一个xml ...

  2. 序列化和反序列化在浏览器和 Web 服务器之间传递的数据、加密解密

    js中数组不能传递到后台,需进行json序列化: var data = new Array(); data.push({para1:name,para2:answer}); string data = ...

  3. Android:客户端和服务器之间传输数据加密

    Android客户端与服务器进行数据传输时,一般会涉及到两类数据的加密情况,一类是只有创建者才能知道的数据,比如密码:另一类是其他比较重要的,但是可以逆向解密的数据. 第一类:密码类的数据,为了让用户 ...

  4. Android Fragment之间传递List数据

    要说的是在两个Fragment之间传递List数据,比如有个List<User>,以及传递字符串数据,比如testId,该如何从FragmentA传递到FragmentB呢? 下面这个例子 ...

  5. 利用AXIS2传递JSON数据

    Axis2是目前比较流行的WebService引擎.WebService被应用在很多不同的场景.例如,可以使用WebService来发布服务端 Java类的方法,以便使用不同的客户端进行调用.这样可以 ...

  6. Android客户端与服务器

    就是普通的服务器端编程,还不用写界面,其实还比服务器编程简单一些.跟J2EE一样的服务器,你android这一方面只要用json或者gson直接拿数据,后台的话用tomcat接受请求操作数据,功能不复 ...

  7. Android客户端与服务器交互方式-小结

    最近的Android项目开发过程中一个问题困扰自己很长时间,Android客户端与服务器交互有几种方式,最常见的就是webservices和json.要在Android手机客户端与pc服务器交互,需要 ...

  8. Ajax(form表单文件上传、请求头之contentType、Ajax传递json数据、Ajax文件上传)

    form表单文件上传 上菜 file_put.html <form action="" method="post" enctype="multi ...

  9. Android学习总结——Activity之间传递参数

    核心内容:一.在 Activity 之间传递简单数据二.在 Activity 之间传递复杂数据 三.在 Activity 之间传递自定义值对象   软件环境:Android Studio   一.在 ...

随机推荐

  1. hdu acmsteps 2.1.3 Cake

    Cake Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submissi ...

  2. windows搭建openacs编译环境

    1.下载ant工具用来编译openacs源码 apache-ant-1.8.2 下载地址http://ant.apache.org/ 这个文件不用编译,在目录bin/下有针对windows的ant 2 ...

  3. ASP.NET MVC 中将数据从View传递到控制器中的三种方法(表单数据绑定)

    http://www.cnblogs.com/zyqgold/archive/2010/11/22/1884779.html 在ASP.NET MVC框架中,将视图中的数据传递到控制器中,主要通过发送 ...

  4. Linux 安装Rsync和配置

    1.检查rsync 是否已经安装 [root@test home]# rpm -qa|grep rsync 若已经安装,则使用rpm -e 命令卸载. [root@test home]#rpm -e ...

  5. Windows 下安装项目管理工具 Redmine 1.1.2

    1.InstantRails-2.0-win 下载地址  https://rubyforge.org/frs/?group_id=904 2.redmine1.1.2 下载地址  http://www ...

  6. C++中的vector使用范例

    原文链接 http://blog.csdn.net/tjh666/article/details/1604119 1.vector 的数据的存入和输出: #include<stdio.h> ...

  7. Minimum Depth of Binary Tree

    二叉树的最小深度 采用递归的方式求左右结点的高度,注意判断一个结点是否是叶子结点(左右子树都不存大). int minDepth(TreeNode *root) { return minDepth(r ...

  8. HDU1711

    Number Sequence Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) ...

  9. SHSEE 备战最后十(四)天日记

    努力. Day -1 看书.睡觉. Day 0 上午考试.语文纯RP题跪.理总不错. 下午上课,各种神. Day 1 上午下午讲课...Day 0成绩出来才#17.... Day 2 考试..这次题目 ...

  10. Resumable Media Uploads in the Google Data Protocol

    Eric Bidelman, Google Apps APIs team February 2010 Introduction The Resumable Protocol Initiating a ...