代码中,需要将前端传来的经过hashids
加密的数据进行解密,再提供给方法使用,故通过JsonDeserializer来进行实现
/**
* hashids json反序列化
*/
public class HashidsCollectionJsonDeserialize extends JsonDeserializer {
@SneakyThrows
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// 获取数组节点
ArrayNode treeNode = p.readValueAsTree();
// 获取当前对象
Object currentValue = p.getCurrentValue();
// 获取对象属性
Field field = currentValue.getClass().getDeclaredField(p.getCurrentName());
// 获取属性泛型,
ResolvableType resolvableType = ResolvableType.forField(field);
Class<?> fieldGenericType = resolvableType.getGeneric(0).resolve();
// 获取迭代器
Iterator<JsonNode> elements = treeNode.elements();
if (Long.class == fieldGenericType) {
List<Long> list = new ArrayList<>(treeNode.size());
// 迭代元素
while (elements.hasNext()) {
String hash = elements.next().asText();
try {
list.add(HashidsUtil.decodeLong(hash));
} catch (Exception e) {
// 解析失败时,返回-1,以便后续抛出DATA_NOT_EXIST异常
list.add(-1L);
}
}
return list;
} else {
// 迭代元素
List<String> list = new ArrayList<>(treeNode.size());
while (elements.hasNext()) {
String hash = elements.next().asText();
list.add(HashidsUtil.decodeString(hash));
}
return list;
}
}
}