Android-Iphone運用Http協議使用Json格式進行服務器端和客戶端通信

[color=green]測試類pojo和json打太極[/color]


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());
}
}
[color=red] [size=large]在action中調用[/size][/color]
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();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章