将字符串转换成json格式
1.引入json依赖,在pom.xml文件里添加如下内容
1 <!--Json array start --> 2 <dependency> 3 <groupId>commons-beanutils</groupId> 4 <artifactId>commons-beanutils</artifactId> 5 <version>1.7.0</version> 6 </dependency> 7 <dependency> 8 <groupId>commons-collections</groupId> 9 <artifactId>commons-collections</artifactId> 10 <version>3.1</version> 11 </dependency> 12 <dependency> 13 <groupId>commons-lang</groupId> 14 <artifactId>commons-lang</artifactId> 15 <version>2.5</version> 16 </dependency> 17 <dependency> 18 <groupId>net.sf.ezmorph</groupId> 19 <artifactId>ezmorph</artifactId> 20 <version>1.0.3</version> 21 </dependency> 22 <dependency> 23 <groupId>net.sf.json-lib</groupId> 24 <artifactId>json-lib</artifactId> 25 <version>2.4</version> 26 <classifier>jdk15</classifier> 27 </dependency> 28 <!--Json array end -->
2.List集合转换成json代码
1 List list = new ArrayList(); 2 list.add( "first" ); 3 list.add( "second" ); 4 JSONArray jsonArray2 = JSONArray.fromObject( list );
3. Map集合转换成json代码
1 Map map = new HashMap(); 2 map.put("name", "json"); 3 map.put("bool", Boolean.TRUE); 4 map.put("int", new Integer(1)); 5 map.put("arr", new String[] { "a", "b" }); 6 map.put("func", "function(i){ return this.arr[i]; }"); 7 JSONObject json = JSONObject.fromObject(map);
4.Bean转换成json代码
1 JSONObject jsonObject = JSONObject.fromObject(new JsonBean());
5.数组转换成json代码
1 boolean[] boolArray = new boolean[] { true, false, true }; 2 JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
6.一般数据转换成json代码
1 JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']" );
7.beans转换成json代码
1 List list = new ArrayList(); 2 JsonBean2 jb1 = new JsonBean2(); 3 jb1.setCol(1); 4 jb1.setRow(1); 5 jb1.setValue("xx"); 6 JsonBean2 jb2 = new JsonBean2(); 7 jb2.setCol(2); 8 jb2.setRow(2); 9 jb2.setValue(""); 10 list.add(jb1); 11 list.add(jb2); 12 JSONArray ja = JSONArray.fromObject(list);
posted on 2017-08-16 10:43 running_wolf 阅读(1251) 评论(0) 编辑 收藏 举报