jar包导入:http://pan.baidu.com/s/1c1Irf4c
person.java
package com.dx.pojo;
public class Person {
private String name;
private String password;
public Person(){};
public Person(String name,String password){
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "Person [name=" + name + ", password=" + password + "]";
}
}
ShopList.java
package com.dx.pojo;
import java.util.List;
public class ShopList {
private List<Person> shopList;
public List<Person> getShopList() {
return shopList;
}
public void setShopList(List<Person> shopList) {
this.shopList = shopList;
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
import com.dx.pojo.Person;
import com.dx.pojo.ShopList;
public class Demo1 {
public static void main(String[] args) throws Exception {
//test1();
//test2();
//test3();
test4();
//test5();
}
//将对象转换程json
public static void test1(){
Person p = new Person("zhangsan","12345");
JSONObject m = JSONObject.fromObject(p);
System.out.println(m.toString());
}
//将map集合转换成json
public static void test2(){
HashMap map = new HashMap();
map.put("name", "zhangsan");
map.put("password", "123456");
JSONObject m = JSONObject.fromObject(map);
System.out.println(m.toString());
}
//将list集合转换成json
public static void test3(){
ArrayList<Person> list = new ArrayList<Person>();
Person p1 = new Person("zhangsan","12345");
Person p2 = new Person("lisi","432445");
list.add(p1);
list.add(p2);
JSONArray m = JSONArray.fromObject(list);
System.out.println(m.toString());
}
//将string转换成bean
public static void test4(){
HashMap<String,Object> map = new HashMap<String,Object>();
map.put("shopList", Person.class);
String person = "{name:'zhangsan',password:'1233432'}";
Person p = (Person) JSONObject.toBean(JSONObject.fromObject(person), Person.class);
System.out.println(p);
//转换成集合对象
String persons = "{'shopList':[{name:'zhangsan',password:'1233432'},{name:'zhangsan',password:'1233432'}]}";
ShopList list = (ShopList)JSONObject.toBean(JSONObject.fromObject(persons), ShopList.class,map);
List<Person> l = list.getShopList();
for(int i = 0; i < l.size(); i++){
System.out.println(l.get(i));
}
}
//将json转换成xml
public static void test5(){
String person = "{name:'zhangsan',password:'1233432'}";
JSONObject o = JSONObject.fromObject(person);
XMLSerializer out = new XMLSerializer();
System.out.println(out.write(o));
}
}