JSON解析

//客户端

@SuppressWarnings("unchecked")
 public String doParser() throws Exception {

  // 在测试过程中,经常是用本机做测试服务器,访问本机的IP地址要设置为10.0.2.2
  String url = "http://10.0.10.232:8080/JsonDemo/json";
  String body =  readParse(url);
  StringBuffer sb = new StringBuffer();
  JSONArray array = new JSONArray(body);
  for (int i = 0; i < array.length(); i++) {
   JSONObject obj = array.getJSONObject(i);
   Iterator<String> iter = obj.keys();
   while (iter.hasNext()) {
    String key = iter.next();
    if (key != null && !"".equals(key)) {
     if (key.equals("id")) {
      sb.append("id:").append(obj.opt("id"))
        .append("\t\n");
     } else if (key.equals("name")) {
      sb.append("name:").append(obj.opt("name"))
        .append("\r\n");
     } else if (key.equals("gender")) {
      sb.append("gender:").append(obj.opt("gender"))
        .append("\t\n");
     } else if (key.equals("email")) {
      sb.append("email:").append(obj.opt("email"))
        .append("\r\n");
     } else if (key.equals("address")) {
      sb.append("address:[");// .append(obj.get("address")).append("\r\n");
      JSONObject adss = obj.optJSONObject("address");
      sb.append("country:").append(adss.opt("country"))
        .append(",");
      sb.append("province:").append(adss.opt("province"))
        .append("]").append("\r\n");
     }
    }
   }
   sb.append("----------------------\r\n");
  }

  return sb.toString();
 }


public static String readParse(String urlPath) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
try {
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();
} catch (Exception e) {
// TODO: handle exception
}
return new String(outStream.toByteArray());
}

 


//服务器端 准备数据

package com.cn.json;

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

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.cn.bean.Address;
import com.cn.bean.User;

public class prepareData {
 private List<User> list;

 public JSONArray jsonData() {
  data();
  // JSON数组
  JSONArray array = new JSONArray();
  for (User bean : list) {
   // 单个用户JSON对象
   JSONObject obj = new JSONObject();
   try {
    obj.put("id", bean.getId());
    obj.put("", bean.getName());
    obj.put("email", bean.getEmail());
    obj.put("gender", bean.getGender());
    obj.put("address", bean.getAddress());
   } catch (Exception e) {
    e.printStackTrace();
   }
   array.add(obj);
  }
  return array;
 }

 private void data() {
  list = new ArrayList<User>();
  User bean1 = new User();
  bean1.setId(1001);
  bean1.setName("Tony");
  bean1.setEmail("tony@toeach.net");
  bean1.setGender("male");
  Address address1 = new Address();
  address1.setCountry("china");
  address1.setProvince("beijing");
  bean1.setAddress(address1);
  list.add(bean1);

  User bean2 = new User();
  bean2.setId(1002);
  bean2.setName("Jack");
  bean2.setEmail("jack@hotmail.com");
  bean2.setGender("male");
  Address address2 = new Address();
  address2.setCountry("china");
  address2.setProvince("shanghai");
  bean2.setAddress(address2);
  list.add(bean2);

  User bean3 = new User();
  bean3.setId(1003);
  bean3.setName("Marry");
  bean3.setEmail("marry@163.com");
  bean3.setGender("female");
  Address address3 = new Address();
  address3.setCountry("china");
  address3.setProvince("henan");
  bean3.setAddress(address3);
  list.add(bean3);

  User bean4 = new User();
  bean4.setId(1004);
  bean4.setName("Linda");
  bean4.setEmail("linda@21cn.com");
  bean4.setGender("female");
  Address address4 = new Address();
  address4.setCountry("china");
  address4.setProvince("jiangsu");
  bean4.setAddress(address4);
  list.add(bean4);
 }
}

//服务器端 servlet

package com.cn.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import com.cn.json.prepareData;

public class JSONDemoServlet extends HttpServlet {

 /**
  *
  */
 private static final long serialVersionUID = 1L;

 

 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  response.setContentType("text/html");
  response.setCharacterEncoding("UTF-8");
  PrintWriter out = response.getWriter();
  // 准备用户数据
  prepareData data=new prepareData();
  JSONArray array=data.jsonData();
  // 输出
  out.write(array.toString());
  out.flush();
  out.close();
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  doGet(request, response);
 }

 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值