JSON是一种很简洁很重要的数据格式,通常用来交换传输数据,广泛使用于JavaScript技术中,并逐渐在各种流行编程语言中火了起来。在Java中也有一个JSON的库,用来重要作用就是Java对象与JSON、XML数据的相互转换,有着重要的应用。9 k G* R2 p' x+ i0 X
环境:JDK5 , json-lib-2.3-jdk15/ O7 _+ x/ |1 g6 D8 a3 q+ [
所依赖的包: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' f5 U7 D8 R! Q7 ?, z
java中各种类型所对应的json格式:# F/ g( Z. V% o7 _* Z7 j
1.数组或集合-->JSON串
! p; j1 U2 {! N% ~. G7 B public static void test1() {( Z! _7 O% e. s7 v
System.out.println("------------数组或集合-->JSON串----------");
- s/ O- x- ~' C3 W/ t" }+ n boolean[] boolArray = new boolean[]{true, false, true};- S# f' K$ ]1 g5 j9 T; y& O. `
JSONArray jsonArray1 = JSONArray.fromObject(boolArray);9 g5 W( D) t% G E
System.out.println(jsonArray1);
* `4 @! S" ~" }! U( L4 J //输出格式: [true,false,true]5 B/ e2 @8 G3 [ r9 Q7 @) i
List list = new ArrayList();
5 Q t7 ~ J& Z9 n" o5 V1 z! X list.add("first");
2 ]) y1 Y) F/ v6 c1 W& A list.add("second");
d; R' U+ f; k* Q! f6 c2 u/ l/ f JSONArray jsonArray2 = JSONArray.fromObject(list);
{! k: d7 y8 ?* X1 B7 @ System.out.println(jsonArray2);
9 B# i# x n }$ N //输出格式: ["first","second"]3 A' N- p) A$ |% I
JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']");
& `- ~4 G* ^/ W% Q: w! C% s System.out.println(jsonArray3);$ e" e* Y& J0 Y7 {4 L
//输出格式: ["json","is","easy"]
! t, @) I7 \2 @. ]; c+ [' ^ }; X E0 `" {; _9 Q* z. G9 R
2.Object|Map-->JSON串
; A' c% L' `: l0 Z public static void test2() {% p3 v/ Z+ }& a2 Y/ b+ y( q' J: |
System.out.println("------------Object|Map-->JSON串----------");* Z: T0 q; H9 A' l
Map map = new HashMap();
: N* M+ J) ?; l( b& p% e: |3 ` map.put("name", "json");
2 L9 A9 u* y; p map.put("bool", Boolean.TRUE); L% O E3 g4 c
map.put("int", new Integer(1));; a" h# U1 f# Z, R: `
map.put("arr", new String[]{"a", "b"});' `9 D' C. a4 j2 N3 y* c2 s+ E* p
map.put("func", "function(i){ return this.arr; }");7 k* x6 h3 H! A9 P- Y' S/ A# U2 o
JSONObject jsonObject1 = JSONObject.fromObject(map);
7 j* ?( B _* i. x# s System.out.println(jsonObject1);
# q* n% ~9 O. h9 m //输出格式: {"func":function(i){ return this.arr; },"arr":["a","b"],"int":1,"bool":true,"name":"json"}9 p$ ]+ i0 E* j- b4 s" _
JSONObject jsonObject2 = JSONObject.fromObject(new MyBean());) {' V( W9 N$ z9 ^* J: l) H
System.out.println(jsonObject2);
5 D0 Y F" q- ]; O. O( r7 {/ T/ K9 J //输出格式: {"func1":function(i){ return this.options; },"func2":function(i){ return this.options; },"name":"json","options":["a","f"],"pojoId":1}& D$ F. o( S0 i; B" {
} |