日期:2014-05-17 浏览次数:21319 次
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;
public class PeopleBean {
private String name;
private int age;
private boolean gendar;
//setter/getter
public PeopleBean() {
}
public PeopleBean(String name, int age, boolean gendar) {
this.name = name;
this.age = age;
this.gendar = gendar;
}
public static void main(String[] args) throws Exception{
/**
* 创建JSONObject对象
*/
//Create a JSONObject from scratch
JSONObject object1=new JSONObject();
object1.element("name", "张三");
object1.element("age", 24);
object1.element("gendar", true);
//Create a JSONObject from formatted String
String jsonString1="{name:\"李四\",age:25,gendar:false}";
JSONObject object2=JSONObject.fromObject(jsonString1);
String jsonString2="{'name':'王五','age':22,'gendar':true}";
JSONObject object3=(JSONObject)JSONSerializer.toJSON(jsonString2);
//Create a JSONObject from a Map
Map map=new HashMap();
map.put("name", "刘六");
map.put("age", 23);
map.put("gendar", true);
JSONObject object4=(JSONObject)JSONSerializer.toJSON(map);
//Create a JSONObject from a bean
PeopleBean WangNan=new PeopleBean("王l",26,true);
JSONObject object5=(JSONObject)JSONSerializer.toJSON(WangNan);
/**
* 把JSONObject对象转化为Bean或Object
*/
PeopleBean people=(PeopleBean)object5.toBean(object5, PeopleBean.class);
System.out.println("name===="+people.getName()+" age======"+people.getAge()+" gendar======"+people.isGendar());
/**
* From JSON to XML
*/
JSONObject object6=new JSONObject(true);
XMLSerializer xmlSerializer=new XMLSerializer();
String xml1=xmlSerializer.write(object6);
System.out.println(xml1);
xmlSerializer.setRootName("people");
xmlSerializer.setTypeHintsEnabled(false);
String xml2=xmlSerializer.write(object5);
System.out.println(xml2);
/**
* From XML to JSON
*/
JSONObject object7=(JSONObject)xmlSerializer.read(xml2);
System.out.println(object7);
}
}
import net.sf.json.JSONObject; import net.sf.json.JSONSerializer; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction1b0004:0:3;402881c42d8