日期:2014-05-16 浏览次数:20389 次
下载
?
json-lib依赖包:
?
java转json
?
通常用可以用两个不同的类可以完成转换:JSONObject,JSONSerializer
?
?
public class Address {
private String street;// 街道
private String city;// 城市
private int zip;// 邮编
private String tel;// 第一个电话号码
private String telTwo;// 第二个电话号码
?
public Address() {
}
?
public Address(String street, String city, int zip, String tel,
String telTwo) {
this.street = street;
this.city = city;
this.zip = zip;
this.tel = tel;
this.telTwo = telTwo;
}
?
public String getStreet() {
return street;
}
?
public void setStreet(String street) {
this.street = street;
}
?
public String getCity() {
return city;
}
?
public void setCity(String city) {
this.city = city;
}
?
public int getZip() {
return zip;
}
?
public void setZip(int zip) {
this.zip = zip;
}
?
public String getTel() {
return tel;
}
?
public void setTel(String tel) {
this.tel = tel;
}
?
public String getTelTwo() {
return telTwo;
}
?
public void setTelTwo(String telTwo) {
this.telTwo = telTwo;
}
?
}
?
//处用JSONObject从java转换json
public class JSONObjectTest extends TestCase {
public void testDate2Json() {
JSONObject jsonObj = JSONObject.fromObject(new Date());
System.out.println(jsonObj.toString());
}
?
public void testArray2Json() {
JSONArray jarray = JSONArray.fromObject(new String[][] {
{ "one", "two" }, { "three", "four" } });
System.out.println(jarray.toString());
JSONArray arr = JSONArray.fromObject(jarray.toString());
System.out.println(((JSONArray) arr.get(1)).get(0));
}
?
public void testList2Json() {
List list = new ArrayList();
list.add(new Integer(1));
list.add(new Boolean(true));
list.add(new Character('j'));
list.add(new char[] { 'j', 's', 'o', 'n' });
list.add(null);
list.add("json");
list.add(new String[] { "json", "-", "lib" });
list.add(new JSONFunction(new String[] { "i" }, "alert(i)"));
list.add(new Address("P.O BOX 54534", "Seattle, WA", 42452,
"561-832-3180", "531-133-9098"));
JSONArray arr=JSONArray.fromObject(list);
System.out.println(arr.toString(4));
arr=JSONArray.fromObject(list);