首先需要引入以下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