java - 如何告诉杰克逊在反序列化时忽略某些字段
问题描述
我正在调用一个端点,它在其中返回一个对象。在这个对象中,它包含一些字段以及另一种对象的字段。例如
class ResponseObject{
private final boolean success;
private final String message;
private final DifferentType different;
}
我通过 RestTemplate 调用端点:
private LogonResponseMessage isMemberAuthenticated(UserCredentialDomain userCredentialDomain)
{
RestTemplate restTemplate = new RestTemplate();
return restTemplate.getForObject(
"http://abc.local:8145/xyz/member/authenticate/{memberLoginName}/{password}", ResponseObject.class,
userCredentialDomain.getUsername(), userCredentialDomain.getPassword());
}
所以我的消费应用程序给出了这个错误:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `fgh.thg.member.DifferentTypeABC` (no Creators, like default constructor, exist): cannot deserialize from Object v
alue (no delegate- or property-based Creator)
我知道它告诉我在 DifferentTypeABC 类中放置一个默认构造函数,以便让杰克逊反序列化它,但我不能轻易做到这一点,因为我需要更新对不同类型ABC 所在应用程序的依赖关系。回购。
所以我想知道是否有一种方法可以在消费应用程序上配置 RestTemplate 或 jackson,以便如果它不包含默认构造函数,它会忽略尝试反序列化对象?老实说,我对响应对象上的success
andmessage
字段非常感兴趣。
解决方案
解决问题的另一种方法是DifferentType
在此模块中使用Jackson creator Mixin
. 下面是一个例子:
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(mapper.getVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
mapper.addMixIn(DifferentType.class, DifferentTypeMixin.class);
String raw = "{\"message\": \"ok\", \"differentType\": {\"name\": \"foo bar\"}}";
ResponseObject object = mapper.readValue(raw, ResponseObject.class);
System.out.println(mapper.writeValueAsString(object));
}
@Data
static class ResponseObject {
private String message;
private DifferentType differentType;
}
static class DifferentType {
private String name;
public DifferentType(String name) {
this.name = name;
}
}
public static abstract class DifferentTypeMixin {
@JsonCreator
DifferentTypeMixin(@JsonProperty("name") String name) {
}
}
}
推荐阅读
- python - 根据另一列的条件从 Pandas 数据框中删除重复项
- c# - 我的 c# TCP Sockets 程序被 Windows Defender 隔离
- python - 为具有相似模式的列名创建 matplotlib 子图
- java - 未找到 spring-boot-starter-validation
- python - Python - 到期收益率(金融 - 债券)
- gradle - 如何将 Realm 添加到 Kotlin 多平台库项目的 Android 目标?
- ansible - Ansible 无法运行任何命令或 shell
- brute-force - 使用 Hydra 暴力破解 http 摘要
- javascript - 如何通过dms(discord.js v12)检查用户是否在服务器中具有角色
- microsoft-graph-api - Microsoft Graph API / C# SDK can't find Security Group by Display Name