`
lw4135
  • 浏览: 44681 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

Android-Iphone运用Http协议使用Json格式进行服务器端和客户端通信

    博客分类:
  • json
 
阅读更多
测试类pojo和json打太极

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;
/**
 * JSON对象和pojo的互相转换
 * 
 * 运用的ezmorph-1.0.2.jar
 * @author myth
 *
 */
public class JSONTestForStruts {

	/**
	 * 将普通的pojo(Plain Old Java Objects)转换成JSON字符串
	 * @return
	 */
	public  JSONObject bean2json() {
		User user = new User();
		user.setId("JSONTest");
		user.setName("JSONTest");
		user.setPassword("JSON");
		user.setSay("Hello,i am JSONTest.java");
		JSONObject jsonObject = new JSONObject();
		
		ArrayList<User> list=new ArrayList<User>();
		list.add(user);
		list.add(user);
		
		Map<Integer, String> map = new HashMap<Integer, String>();
		map.put(220180, null);
		map.put(220181, "Json测试类");
		
		jsonObject.accumulate("user", user);//accumulate累加
		jsonObject.accumulate("list", list);
		jsonObject.accumulate("map", map);
		System.out.println("User转换成JSON格式的字符串:"+jsonObject.toString());
		return jsonObject;
	}

	/**
	 * 从JSONObject对象中反向解析出User对象
	 * @param jsonObject
	 */
	public  void json2bean(JSONObject jsonObject) {
		User user=(User)JSONObject.toBean((JSONObject)jsonObject.get("user"),User.class);
		System.out.println("转换得到的User对象的Name为:"+user.getName());
	}

	public static void main(String[] s) {
		JSONTestForStruts jsonTest=new JSONTestForStruts();
		jsonTest.json2bean(jsonTest.bean2json());
	}
}
在action中调用
response.setContentType("text/html;charset=gbk");
		 PrintWriter out=response.getWriter();
		//将要被返回到客户端的对象
		JSONObject json=new JSONObject();
		json.accumulate("success", true);
		json.accumulate("esff", esff);
		out.println(json.toString());
		out.flush();
		out.close();
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics