Java基本資料轉換成Json代碼,java資料轉換json
JSON是一種輕量級的資料交換格式,非常適合於伺服器與 JavaScript 的互動。是移動開發中資料用戶端和伺服器端資料互動的不二選擇; 尤其是現在HTML5的流行,更顯著使用Json 完成資料互動的重要性. 在這裡, 我將示範一下Java基本資料轉換為Json代碼
Json必需包
如果不想自己下載jar 可以使用這個demo
1.List集合轉換成json代碼
List<Person> list = new ArrayList<Person>(); list.add(new Person(0,"nagi_ho", 20,"海澱")); list.add(new Person(1, "eson_ho", 21,"朝陽")); JSONArray jsonList = JSONArray.fromObject(list); System.out.println("1.List集合轉換成json代碼====>" + jsonList.toString());
2.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[] { "btbu", "b" }); map.put("func", "function(i){ return this.arr; }"); JSONObject jsonMap = JSONObject.fromObject(map); System.out.println("2.Map集合轉換成json代碼====>"+jsonMap.toString());
3.Set集合轉換成json代碼
Set<Person> set = new HashSet<Person>(); set.add(new Person(0, "nagi_ho", 20,"信管112")); set.add(new Person(1, "eson_ho", 22,"電商112")); JSONArray jsonArray4 = JSONArray.fromObject(set); System.out.println("3.Set集合轉換成json代碼====>" +jsonArray4.toString());
4.Bean轉換成json代碼
JSONObject jsonObject = JSONObject.fromObject(new Person(1, "信管112", 22,"btbu")); System.out.println("4.Bean轉換成json代碼====>"+jsonMap.toString());
5.數群組轉換成json代碼
boolean[] boolArray = new boolean[] { true, false, true }; String[] stringArray = new String[] {"信管111","信管112", "電商111", "電商112"}; JSONArray boolArray1 = JSONArray.fromObject(boolArray); JSONArray jsonArray2 = JSONArray.fromObject(stringArray); System.out.println("5.數群組轉換成json代碼====>"+boolArray1.toString()); System.out.println("5.數群組轉換成json代碼====>"+jsonArray2.toString());
6.一般資料轉換成json代碼
JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']" ); System.out.println("6.一般資料轉換成json代碼====>"+jsonArray3.toString());
運行結果:
1.List集合轉換成json代碼====>[{"address":"海澱","age":20,"id":0,"name":"nagi_ho"},{"address":"朝陽","age":21,"id":1,"name":"eson_ho"}]2.Map集合轉換成json代碼====>{"arr":["btbu","b"],"int":1,"name":"json","func":function(i){ return this.arr; },"bool":true}3.Set集合轉換成json代碼====>[{"address":"電商112","age":22,"id":1,"name":"eson_ho"},{"address":"信管112","age":20,"id":0,"name":"nagi_ho"}]4.Bean轉換成json代碼====>{"arr":["btbu","b"],"int":1,"name":"json","func":function(i){ return this.arr; },"bool":true}5.數群組轉換成json代碼====>[true,false,true]5.數群組轉換成json代碼====>["信管111","信管112","電商111","電商112"]6.一般資料轉換成json代碼====>["json","is","easy"]
當然我相信大家對這個json 格式不滿意, 那麼我們使用json的格式化工具Hison( 點擊下載)
[ { "address":"北京", "age":20, "id":0, "name":"nagi" }, { "address":"北京", "age":21, "id":1, "name":"nag1" }, { "address":"北京", "age":22, "id":2, "name":"nag2" }, { "address":"北京", "age":23, "id":3, "name":"nag3" }, { "address":"北京", "age":24, "id":4, "name":"nag4" }]
這樣是不是看起來很爽了, 試一試吧,
如果覺得對你有用 給個贊吧~
Demo完整源碼下載