Json常用的类库如下
Jackson:http://jackson.codehaus.org/
JSON-lib:http://json-lib.sourceforge.net/
Gson:http://code.google.com/p/google-gson/
Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象。不仅限于对java对象,对于Map、List、Array同样有效。
JsonLib的教程参考之前我写过的文章:http://blog.csdn.net/xiaokui_wingfly/article/details/39890969
或其他朋友的文章:http://www.cnblogs.com/hoojo/archive/2011/04/21/2023805.html
XStream : http://blog.csdn.net/xiaokui_wingfly/article/details/46470145
一、准备工作
1、 下载依赖库jar包
Jackson的jar官方下载地址:http://wiki.fasterxml.com/JacksonDownload
然后在工程中导入这个jar包即可开始工作
官方示例:http://wiki.fasterxml.com/JacksonInFiveMinutes
如果你需要转换xml,那么还需要stax2-api.jar
注:以下我的所有示例中省略getter和setter方法,请自行添加
示例1:一个简单的Json和JavaBean之间的转换
/** * JavaBean/Map/List/Array互相转换JSON */ public static void main(String[] args) { ObjectMapper objectMapper = new ObjectMapper(); User user = new User(); user.setAddress("中国河南省"); user.setEmail("xiaokui_wingfly@sina.com.cn"); user.setId(1); user.setName("X-rapido"); user.setBirthday(new Birthday("2015-08-06")); List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); list.add("c"); Map<String, Object> map = new HashMap<String, Object>(); map.put("a", "1"); map.put("b", "2"); map.put("c", "3"); map.put("list", list); String []sz = {"a","b","c"}; try { System.out.println(objectMapper.writeValueAsString(user)); System.out.println(objectMapper.writeValueAsString(list)); System.out.println(objectMapper.writeValueAsString(map)); System.out.println(objectMapper.writeValueAsString(sz)); String s = "{\"name\":\"X-rapido\"}"; // Json转换JavaBean User a = objectMapper.readValue(s, User.class); System.out.println(a.getName()); // JavaBean转换Json System.out.println(objectMapper.writeValueAsString(a)); } catch (IOException e) { e.printStackTrace(); } } 输出打印: {"id":1,"name":"X-rapido","email":"xiaokui_wingfly@sina.com.cn","address":"中国河南省","birthday":{"birthday":"2015-08-06"}} ["a","b","c"] {"b":"2","c":"3","a":"1","list":["a","b","c"]} ["a","b","c"] X-rapido {"id":0,"name":"X-rapido","email":null,"address":null,"birthday":null}
对于如何与xml进行交互和JsonGenerator类的用法还有各个write、writeObject方法参考网友文章http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html 不再罗嗦了。