在我们调用三方平台接口时,经常需要将我们封装的实体类转换为json作为传参,或者是当我们接收报文时接收的为json数据想要转换为我们自己封装的实体类。
- public static void main(String[] args) throws JsonProcessingException {
- user user = new user();
- user.setId(1001);
- user.setUsername("张三");
- user.setPassword("123456");
- user.setTeach(false);
- System.out.println(user);
- ObjectMapper objectMapper=new ObjectMapper();
- String value = objectMapper.writeValueAsString(user);
- System.out.println(JSON.toJSONString(user));
- System.out.println(value);
- }
结果:
- public static void main(String[] args) throws JsonProcessingException {
- JSONObject jsonObject = new JSONObject();
- jsonObject.put("id",1001);
- jsonObject.put("username","张三");
- jsonObject.put("teach","false");
- jsonObject.put("password","123456");
- jsonObject.put("student","1");
- ObjectMapper objectMapper=new ObjectMapper();
- user user = objectMapper.readValue(jsonObject.toString(), user.class);
- System.out.println(user);
- }
需要注意的是如果我们的json数据有五个字段而实体类中只有四个字段的话无法一 一映射会报错
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "student" (class com.newstart.model.user), not marked as ignorable (4 known properties: "id", "teach", "username", "password"])
at [Source: (String)"{"password":"123456","student":"1","teach":"false","id":1001,"username":"张三"}"; line: 1, column: 33] (through reference chain: com.newstart.model.user["student"])
所以我们需要在对应的实体类上加一个注解
@JsonIgnoreProperties(ignoreUnknown = true)该注解的作用是在将实体类进行json序列化和反序列化时可以将无法映射的属性忽略,针对的是jackson。如果fastjson则不存在这个问题,会自动给忽略不存在的属性
结果:
此外还有很多种转换方式!!!