jackson是springboot中集成的序列化方式,是默认的json序列化方式,当然你可以使用其它的序列化工具代替它,不过今天我们还是说一下它,使用jackson进行序列化一个类,然后再把它的JSON字符反序列化为它的接口对象。

现实

  1. 这种方式默认是不行的,因为接口不能被自动实例化
  2. 使用redisTelmplete时,如果使用​​objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);​​这种试序列化,由于会把实例类型写到时 JSON里,所以也不能反序列化为接口

几个序列化方式

一 序列化为具体类型,​​无法反序列化接口​​,即你用什么类型序列化的,就用什么类型反序列化,它经常与redis的序列化Jackson2JsonRedisSerializer一起使用。

ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
User user = new User();
user.setUsername("lind");
user.setEmail("zzl@sina.com");
String msg = om.writeValueAsString(user);

结果

["com.lind.common.JacksonTest$User",{"username":"lind","email":"zzl@sina.com","authorities":null}]

二 序列化为字符串,主要好处是与类型无关,只要字段可以配置上,就可以反序列化,并且在自定义序列化器定义之后,还可以对接口类型进行反序列化,可以说更加方便。
定义一个序列化器

public static class DefaultResourceUserSerializer extends JsonDeserializer<DefaultResourceUser> {

@Override
public DefaultResourceUser deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
DefaultResourceUser userAccountAuthentication = new DefaultResourceUser() {
@Override
public String getUsername() {
return node.get("username").asText();
}

@Override
public String getEmail() {
return node.get("email").asText();
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
Iterator<JsonNode> elements = node.get("authorities").elements();
while (elements.hasNext()) {
JsonNode next = elements.next();
JsonNode authority = next.get("authority");
simpleGrantedAuthorities.add(new SimpleGrantedAuthority(authority.asText()));
}
return simpleGrantedAuthorities;
}
};
return userAccountAuthentication;
}

在接口上使用它
``java
@JsonDeserialize(using = DefaultResourceUserSerializer.class)
public interface DefaultResourceUser {
String getUsername();

String getEmail();

Collection<? extends GrantedAuthority> getAuthorities();
}

代码展现了反序列化一个json字符串
```json
{
"id": "347214418355949568",
"username": "admin",
"password": "{bcrypt}$2a$10$tVrm4VjC9BXF8PStUASZkOJCOm7mKR4ZVDHau.Ug/tm6ZEXEsHhcC",
"nickName": "测试",
"mobile": "",
"email": "",
"address": "北京",
"street": "",
"sex": 0,
"passStrength": "",
"avatar": "",
"type": 0,
"status": 0,
"description": "",
"departmentId": "",
"departmentTitle": null,
"resourcePermissions": [{
"id": "348193374957735936",
"title": "系统管理",
"path": "",
"type": 0,
"parentId": "",
"parent": null,
"sons": null
}, {
"id": "348193687223668737",
"title": "用户管理",
"path": "/user",
"type": 0,
"parentId": "348193374957735936",
"parent": null,
"sons": null
}, {
"id": "348193868908335105",
"title": "添加用户",
"path": "/user/add*",
"type": 0,
"parentId": "348193687223668737",
"parent": null,
"sons": null
}, {
"id": "348193927590842369",
"title": "用户列表",
"path": "/user/list*",
"type": 0,
"parentId": "348193687223668737",
"parent": null,
"sons": null
}, {
"id": "348194428344602626",
"title": "权限管理",
"path": "/permission/**",
"type": 0,
"parentId": "348193374957735936",
"parent": null,
"sons": null
}, {
"id": "348194428344602627",
"title": "权限添加",
"path": "/permission/add*",
"type": 0,
"parentId": "348194428344602626",
"parent": null,
"sons": null
}, {
"id": "348194428344602628",
"title": "角色管理",
"path": "/role/list",
"type": 0,
"parentId": "348193374957735936",
"parent": null,
"sons": null
}, {
"id": "348194428344602629",
"title": "demo",
"path": "/demo",
"type": 0,
"parentId": "348193374957735936",
"parent": null,
"sons": null
}],
"resourceRoles": null,
"enabled": true,
"authorities": [{
"authority": "用户管理"
}, {
"authority": "添加用户"
}, {
"authority": "用户列表"
}, {
"authority": "权限管理"
}, {
"authority": "权限添加"
}, {
"authority": "角色管理"
}, {
"authority": "demo"
}],
"accountNonLocked": true,
"accountNonExpired": true,
"credentialsNonExpired": true
}

代码

@SneakyThrows
@Test
public void stringJackson() {
DefaultResourceUser user = fromJson("jack.json", DefaultResourceUser.class);
log.info("user:{}", user.getUsername());
for (GrantedAuthority grantedAuthority : user.getAuthorities()) {
log.info("auth:{}", grantedAuthority.getAuthority());
}

}

结果

​1​

作者:仓储大叔,张占岭,
荣誉:微软MVP