(废弃)Jackson 处理json(ObjectMapper) 作者:马育民 • 2020-07-10 21:26 • 阅读:10118 [Jackson介绍和目录](https://www.malaoshi.top/show_1EF61Bp7UvwW.html "Jackson介绍和目录") # 废弃 见 [Jackson 处理json-准备(ObjectMapper)](https://www.malaoshi.top/show_1IX34L64qmuf.html "Jackson 处理json-准备(ObjectMapper)") # ObjectMapper 功能强大,本文介绍: 1. 使用 ObjectMapper 类将POJO对象序列化成JSON字符串 2. 将JSON字符串反序列化成POJO对象 3. 通过response输出json # 依赖 ### 添加jar包 - 普通工程 依赖 jackson jar包,将 javabean 转换成 json: - jackson-annotations-2.3.1.jar - jackson-core-2.3.1.jar - jackson-databind-2.3.1.jar ### 修改pom.xml - maven工程 ``` com.fasterxml.jackson.core jackson-databind 2.9.1 ``` jackson-databind 依赖 jackson-core 和 jackson-annotations,当添加 jackson-databind 之后, jackson-core 和 jackson-annotations 也随之添加到 Java 项目工程中。在添加相关依赖包之后,就可以使用 Jackson。 # 将java对象转成json ### 注意 javabean至少有一个成员变量有 `getter` 方法,如果没有成员变量,或者没有 `getter` 方法,会 **报错如下**: ``` com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class vo.JsonResult and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) ``` ### 将javabean转成json 代码: ``` public class JsonResult { private int code; private String msg; public JsonResult(int code, String msg) { this.code = code; this.msg = msg; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } ``` 转换代码: ``` JsonResult result=new JsonResult(); result.setCode(10000); result.setMsg("请登录!"); ObjectMapper om=new ObjectMapper(); String json=om.writeValueAsString(result); ``` ### List转换json ``` List list = new ArrayList(); list.add(1); list.add(2); list.add(3); ObjectMapper mapper = new ObjectMapper(); try { String json = mapper.writeValueAsString(list); System.out.println(json); } catch (JsonProcessingException e) { e.printStackTrace(); } ``` 执行结果: ``` [1,2,3] ``` 复杂: ``` Map map1=new HashMap(); map1.put("name","root"); map1.put("pwd","123456"); Map map2=new HashMap(); map2.put("name","user"); map2.put("pwd","user"); List list = new ArrayList(); list.add(map1); list.add(map2); ObjectMapper mapper = new ObjectMapper(); try { String json = mapper.writeValueAsString(list); System.out.println(json); } catch (JsonProcessingException e) { e.printStackTrace(); } ``` 执行结果: ``` [{"name":"root","pwd":"123456"},{"name":"user","pwd":"user"}] ``` ### Map转成json ``` Map map = new HashMap<>(); map.put("username", "root"); map.put("password", "123456"); ObjectMapper mapper = new ObjectMapper(); try { String json = mapper.writeValueAsString(map); System.out.println(json); } catch (JsonProcessingException e) { e.printStackTrace(); } ``` 执行结果: ``` {"password":"123456","username":"root"} ``` # json转成java对象 ### json转javabean ``` String json = "{\"code\":10000,\"msg\":\"请登录!\"}"; ObjectMapper mapper = new ObjectMapper(); JsonResult result = mapper.readValue(json, JsonResult.class); ``` ### json转list ##### 简单: ``` String json="[1,2,3]"; ObjectMapper mapper = new ObjectMapper(); try { List list=mapper.readValue(json,List.class); for(Integer item:list){ System.out.println(item); } } catch (JsonProcessingException e) { e.printStackTrace(); } ``` 执行结果: ``` 1 2 3 ``` ##### 复杂: 先要先反序列化复杂类型 使用ObjectMapper的`getTypeFactory().constructParametricType(Class> parametrized, Class>... parameterClasses)`方法 ``` String json="[{\"name\":\"root\",\"pwd\":\"123456\"},{\"name\":\"user\",\"pwd\":\"111111\"}]"; ObjectMapper mapper = new ObjectMapper(); JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, Student.class); try { List list=mapper.readValue(json,javaType); for(Student std:list){ System.out.println(String.format("%s--%s", std.getName(),std.getPwd())); } } catch (JsonProcessingException e) { e.printStackTrace(); } ``` Student: ``` class Student{ private String name; private String pwd; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } } ``` 执行结果: ``` root--123456 user--111111 ``` ### json转Map ``` String json="{\"password\":\"123456\",\"username\":\"root\"}"; ObjectMapper mapper = new ObjectMapper(); try { Map map=mapper.readValue(json,Map.class); for(Map.Entry entry:map.entrySet()){ System.out.println(entry.getKey()+"--"+entry.getValue()); } } catch (JsonProcessingException e) { e.printStackTrace(); } ``` # response输出json 通过response输出json ``` Map map=new HashMap<>(); map.put("error",e.getMessage()); response.setCharacterEncoding("utf-8"); response.setContentType("application/json; charset=utf-8"); try { //使用Jackson输出json new ObjectMapper().writeValue(response.getWriter(),map); response.getWriter().flush(); } catch (IOException ioe) { ioe.printStackTrace(); } ``` 原文出处:http://malaoshi.top/show_1EF5rdjyd8U3.html