JSON是一種很簡潔很重要的數據格式,通常用來交換傳輸數據,廣泛使用於Javascript技術中,並逐漸在各種流行編程語言中火了起來。在Java中也有一個JSON的庫,用來重要作用就是Java對象與JSON、XML數據的相互轉換,有著重要的應用。
開源的JSON庫http://JSon-lib.sourceforge.Net/
環境:JDK5 , JSon-lib-2.3-jdk15
所依賴的包:JSon-lib-2.3-jdk15.jar,commons-collections.jar,commons- lang.jar,commons-logging.jar,commons-beanutils.jar,ezmorph- 1.0.6.jar,xom-1.1.jar
Java中各種類型所對應的json格式數組或集合--》JSON串
public static void test1() {
System.out.println(“------------數組或集合--》JSON串----------”);
boolean[] boolArray = new boolean[]{true, false, true};
JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
System.out.println(JSonArray1);
//輸出格式: [true,false,true]
List list = new ArrayList();
list.add(“first”);
list.add(“second”);
JSONArray jsonArray2 = JSONArray.fromObject(list);
System.out.println(JSonArray2);
//輸出格式: [“first”,“second”]
JSONArray jsonArray3 = JSONArray.fromObject(“[‘JSon‘,‘is‘,‘easy‘]”);
System.out.println(JSonArray3);
//輸出格式: [“JSon”,“is”,“easy”]
}
2.Object|Map--》JSON串
public static void test2() {
System.out.println(“------------Object|Map--》JSON串----------”);
Map map = new HashMap();
map.put(“name”, “JSon”);
map.put(“bool”, Boolean.TRUE);
map.put(“int”, new Integer(1));
map.put(“arr”, new String[]{“a”, “b”});
map.put(“func”, “function(i){ return this.arr[i]; }”);
JSONObject jsonObject1 = JSONObject.fromObject(map);
System.out.println(JSonObject1);
//輸出格式: {“func”:function(i){ return this.arr[i]; },“arr”:[“a”,“b”],“int”:1,“bool”:true,“name”:“JSon”}
JSONObject jsonObject2 = JSONObject.fromObject(new MyBean());
System.out.println(JSonObject2);
//輸出格式: {“func1”:function(i){ return this.options[i]; },“func2”:function(i){ return this.options[i]; },“name”:“JSon”,“options”:[“a”,“f”],“pojoId”:1}
}
public class MyBean {
private String name = “JSon”;
private int pojoId = 1;
private char[] options = new char[]{‘a‘, ‘f‘};
private String func1 = “function(i){ return this.options[i]; }”;
private JSONFunction func2 = new JSONFunction(new String[]{“i”}, “return this.options[i];”);
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPojoId() {
return pojoId;
}
public void setPojoId(int pojoId) {
this.pojoId = pojoId;
}
public char[] getOptions() {
return options;
}
public void setOptions(char[] options) {
this.options = options;
}
public String getFunc1() {
return func1;
}
public void setFunc1(String func1) {
this.func1 = func1;
}
public JSONFunction getFunc2() {
return func2;
}
public void setFunc2(JSONFunction func2) {
this.func2 = func2;
}
}