JSON学习三——>网上项目验证(通过)
服务器端:Eclipse + tomcat
/*@author:LKP
*company:mobiscloud
*2011-5-16
*/
public class JSONDemoServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 12323L;
private List<User> list;
/**
* 处理post方式提交的数据
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* 出来get方式提交的数据
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
// 准备用户数据
prepareData();
// JSON数组
JSONArray array = new JSONArray();
for (User bean : list) {
// 单个用户JSON对象
JSONObject obj = new JSONObject();
try {
obj.put("id", bean.getId());
obj.put("name", bean.getName());
obj.put("email", bean.getEmail());
obj.put("gender", bean.getGender());
} catch (Exception e) {
}
array.add(obj);
}
// 输出
out.write(array.toString());
out.flush();
out.close();
}
private void prepareData() {
list = new ArrayList<User>();
User bean1 = new User();
bean1.setId(1001);
bean1.setName("Tony");
bean1.setEmail("tony@toeach.net");
bean1.setGender("male");
list.add(bean1);
User bean2 = new User();
bean2.setId(1002);
bean2.setName("Jack");
bean2.setEmail("jack@hotmail.com");
bean2.setGender("male");
list.add(bean2);
User bean3 = new User();
bean3.setId(1003);
bean3.setName("Marry");
bean3.setEmail("marry@163.com");
bean3.setGender("female");
list.add(bean3);
User bean4 = new User();
bean4.setId(1004);
bean4.setName("Linda");
bean4.setEmail("linda@21cn.com");
bean4.setGender("female");
list.add(bean4);
}
这些都是服务器端的程序,不是很多,比较好了解,前提是一定要搭建好server环境。
Client端程序:
public class MyJSON extends Activity {
TextView tv;
private static final String TAG = "MyJSON";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv);
try {
StringBuffer sb = new StringBuffer();
// 在测试过程中,经常是用本机做测试服务器,访问本机的IP地址要设置为192.168.1.195
String url = "http://192.168.1.195:8080/Webtest/JSONDemoServlet";
String body = getContent(url);
JSONArray array = new JSONArray(body);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
sb.append("id:").append(obj.getInt("id")).append("\t");
sb.append("name:").append(obj.getString("name")).append("\r\n");
sb.append("gender:").append(obj.getString("gender"))
.append("\t");
sb.append("email:").append(obj.getString("email"))
.append("\r\n");
sb.append("----------------------\r\n");
}
tv.setText(sb.toString());
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
}
private String getContent(String url) throws Exception{
StringBuilder sb = new StringBuilder();
HttpClient client = new DefaultHttpClient();
&nbs