Jackson 教程演示样例

查看原文教程:http://www.ibloger.net/article/275.html

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

然后在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方法參考网友文章http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html 不再罗嗦了。

上一篇:Android Button常用法


下一篇:Cocos2d-x 3.2 Lua演示样例 XMLHttpRequestTest(Http网络请求)