首先需要引入以下jar包:
jackson-core-2.2.3.jar(核心jar包)
jackson-annotations-2.2.3.jar(該包提供Json注解支持)
jackson-databind-2.2.3.jar (數據綁定,依賴core、annotations)
注意,databind項目已經自動依賴了jackson-core與jackson-annotation,maven中不需要額外重復引入。
JAVA對象轉JSON[JSON序列化]
/** * ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中實現。 * ObjectMapper有多個JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介質中。 * writeValue(File arg0, Object arg1)把arg1轉成json序列,並保存到arg0文件中。 * writeValue(OutputStream arg0, Object arg1)把arg1轉成json序列,並保存到arg0輸出流中。 * writeValueAsBytes(Object arg0)把arg0轉成json序列,並把結果輸出成字節數組。 * writeValueAsString(Object arg0)把arg0轉成json序列,並把結果輸出成字符串。 */ ObjectMapper mapper = new ObjectMapper(); //User類轉JSON //輸出結果:{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"} String json = mapper.writeValueAsString(user); System.out.println(json); //Java集合轉JSON //輸出結果:[{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}] List<User> users = new ArrayList<User>(); users.add(user); String jsonlist = mapper.writeValueAsString(users); System.out.println(jsonlist);
JSON轉Java類[JSON反序列化]
String json = "{\"name\":\"小民\",\"age\":20,\"birthday\":844099200000,\"email\":\"xiaomin@sina.com\"}"; /** * ObjectMapper支持從byte[]、File、InputStream、字符串等數據的JSON反序列化。 */ ObjectMapper mapper = new ObjectMapper(); User user = mapper.readValue(json, User.class);
ObjectMapper mapper常用的方法
mapper.disable(DeserializationFeature.FALL_ON_UNKNOWN_PROPERTIES);
——當反序列化json時,未知屬性會引起的反序列化被打斷,可以禁用未知屬性打斷反序列化功能
mapper.readValue(byte[] src / File src/ InputStream src, Class<T> classType);
——將給定src結果轉換成給定值類型的方法(從json映射到Java對象)
mapper.configure(SerializationConfig.Feature f, boolean state);
——更改此對象映射器的打開/關閉序列化特性的狀態的方法
更多方法參考:http://tool.oschina.net/uploads/apidocs/jackson-1.9.9/org/codehaus/jackson/map/ObjectMapper.html