1.导入相关jar
<!-- 10.jackson --> <!--10.1 定义了底层的streaming API和实现了Json特性 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.7.3</version> </dependency> <!-- 10.2 实现了数据绑定和对象序列化,它依赖于streaming和annotations的包 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.3</version> </dependency> <!-- 10.3 包含了标准的Jackson注解。本文暂不介绍 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.7.3</version> </dependency> |
2.jackson常用方法记录
2.1 准备实体类
安装lombok插件
https://my.oschina.net/u/4132381/blog/3054137
2.2 对象转json
2.2.1 将所有转json 忽略指定的属性 及null值
需求:
效果:
方式1: 缺点:一个类上定义忽略的字段都会被忽略 别人如果需要就没办法了
@JsonIgnoreProperties({"descr", "other"})//忽略字段 descr, other other 没有用到 这里只是展示忽略多个字段的方式 @JsonInclude(Include.NON_NULL) //忽略 null字段 |
方式2:根据需要自己在代码中忽略相应的字段 需要引入json-lib
效果:
实现方式:
引入:jar
<!--json-lib依赖 --> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> |
代码中:
@RequestMapping("/objectToJson3") public void objectToJson3(HttpServletResponse response) throws IOException{ //设置响应编码格式 response.setContentType("text/html; charset=utf-8"); //------------封装数据------------开始----------------- User2 u = new User2();// //u.setId(2l); u.setName("李四"); u.setDescr("jsonson 配合json-lib 使用 "); u.setOther("json-lib 忽略 不需要的字段"); //------------封装数据------------结束----------------- //--------------------json-lib处理数据--开始------------------------------------------------ JsonConfig jsonConfig = new JsonConfig();//import net.sf.json.JsonConfig; jsonConfig.setExcludes(new String[] {"name","descr"}); JSONArray jsonArray = JSONArray.fromObject(u, jsonConfig);//import net.sf.json.JSONArray; //--------------------json-lib处理数据--结束------------------------------------------------ ObjectMapper mapper=new ObjectMapper(); String jsonData = mapper.writeValueAsString(jsonArray); PrintWriter out = response.getWriter(); out.write(jsonData); out.flush(); out.close(); } |
2.3 list 转 json
效果
方式:
//jackson的核心,通过mapper来进行序列化和反序列化 ObjectMapper mapper=new ObjectMapper(); //序列化,write相关方法!write可以是序列化输出多种格式,当然这边最常用就是写成为String返回前端 String jsonData = mapper.writeValueAsString(list); |
2.4 map 转json
2.4 json转对象
2.5 json转集合
List<User3> resultList = mapper.readValue(jsonData, new TypeReference<List<User3>>(){}); |
2.6 赋值json转对象
2.6.1 对象中含有对象
User4 user4 = mapper.readValue(jsonData, User4.class); // 简单方式 |
2.6.2 对象的属性是集合