​

Json经常使用的类库例如以下

Jackson能够轻松的将Java对象转换成json对象和xml文档。相同也能够将json、xml转换成Java对象。

不仅限于对java对象。对于Map、List、Array相同有效。

一、准备工作

1、 下载依赖库jar包

Jackson的jar官方下载地址:​​http://wiki.fasterxml.com/JacksonDownload​

然后在project中导入这个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方法