Java JSON入门
一、所需jar包
jakarta commons-lang 2.5
jakarta commons-beanutils 1.8.0
jakarta commons-collections 3.2.1
jakarta commons-logging 1.1.1
ezmorph 1.0.6
下载地址:
http://json-lib.sourceforge.net/
http://ezmorph.sourceforge.net/
http://morph.sourceforge.net/
http://www.docjar.com
二、举例(json官网 :http://json-lib.sourceforge.net/usage.html)
1、from beans to json
public class Person { private String username; private String password; } @Test public void demo1() { Person person1 = new Person("aaa", "aaa"); Person person2 = new Person("bbb", "bbb"); List<Person> list = new ArrayList<Person>(); list.add(person1); list.add(person2); JSONArray.fromObject(list); JSONArray jsonArray = JSONArray.fromObject(list); System.out.println( jsonArray.toString()); }
//[{"password":"aaa","username":"aaa"},{"password":"bbb","username":"bbb"}]
from json to beans
class MyBean{ private List data; // getters & setters } class Person{ private String name; // getters & setters } String json = "{'data':[{'name':'Wallace'},{'name':'Grommit'}]}"; Map classMap = new HashMap(); classMap.put( "data", Person.class ); MyBean bean = JSONObject.toBean( JSONObject.fromObject(json), MyBean.class, classMap );
2、from bean to json
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];"); // getters & setters ... } JSONObject jsonObject = JSONObject.fromObject( new MyBean() ); System.out.println( jsonObject ); /* prints {"name":"json","pojoId":1,"options":["a","f"], "func1":function(i){ return this.options[i];}, "func2":function(i){ return this.options[i];}} */
from json to bean
String json = "{bool:true,integer:1,string:\"json\"}"; JSONObject jsonObject = JSONObject.fromObject( json ); BeanA bean = (BeanA) JSONObject.toBean( jsonObject, BeanA.class );