gpt4 book ai didi

java - JsonDeserializer不适用于该类,而仅适用于该类的单个元素

转载 作者:行者123 更新时间:2023-12-03 16:09:35 25 4
gpt4 key购买 nike

我创建了一个新的Deserializer,以便能够将空字符串写为null

public class CustomDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
JsonNode node = jsonParser.readValueAsTree();
if (node.asText().isEmpty()) {
return null;
}
return node.toString();
}
}
尝试在每个User字段上创建单个注释,“自定义”起作用,但是通过在整个类上插入注释,我不再能够打印Json消息
@JsonDeserialize(using = CustomDeserializer.class)
public class User {
private String firstName;
private String lastName;
private String age;
private String address; }
CustomExceptionHandler引发此错误: 类MethodArgumentNotValidException
这是我的Kafka Consumer,是我唯一输入验证注释的人,但即使删除它也会给我同样的错误
public class KafkaConsumer {

@Autowired
private UserRepository userRepository;

@KafkaListener(topics = "${spring.kafka.topic.name}")
public void listen(@Validated User user) {

User user = new User(user);
UserRepository.save(user.getName(), user);
}
}
对象映射器
public ObjectMapper getObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setSerializationInclusion(Include.NON_NULL);
return mapper;
}
是否有可能使它适用于整个类(class)?

最佳答案

如果您希望将表示整个整个对象的空String视为null,则可以启用默认情况下禁用的ACCEPT_EMPTY_STRING_AS_NULL_OBJECT Jackson deserialization feature
您可以在配置ObjectMapper时包括它:

public ObjectMapper getObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setSerializationInclusion(Include.NON_NULL);
// Enable ACCEPT_EMPTY_STRING_AS_NULL_OBJECT deserialization feature
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
return mapper;
}
如上所述,当您要将代表整个对象的整个 的空String视为null时,这很有用;但是,它不适用于String类型的单个属性:在以后的情况下,您可以安全地使用自定义反序列化器,因此,解决方案实际上是两种方法的组合,使用ACCEPT_EMPTY_STRING_AS_NULL_OBJECT反序列化功能来处理整个对象,和用于处理各个String属性的自定义解串器。
请参阅thisthis other相关的SO问题。
您也可以改进自定义的User反序列化器。请考虑一下示例(为了清楚起见,我将名称重构为UserDeserializer):
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;

public class UserDeserializer extends JsonDeserializer<User> {

@Override
public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
JsonNode node = jsonParser.readValueAsTree();
Iterator<String> fieldNames = node.fieldNames();
// Process Jackson annotations looking for aliases
Map<String, String> fieldAliases = this.getAliases();
User user = new User();
boolean anyNonNull = false;
// Iterate over every field. The deserialization process assume simple properties
while(fieldNames.hasNext()) {
String fieldName = fieldNames.next();
JsonNode fieldValue = node.get(fieldName);
String fieldValueTextRepresentation = fieldValue.asText();
if (fieldValueTextRepresentation != null && !fieldValueTextRepresentation.trim().isEmpty()) {
// Check if the field is aliased
String actualFieldName = fieldAliases.get(fieldName);
if (actualFieldName == null) {
actualFieldName = fieldName;
}

this.setFieldValue(user, actualFieldName, fieldValueTextRepresentation);
anyNonNull = true;
}
}

return anyNonNull ? user : null;
}

// Set field value via Reflection
private void setFieldValue(User user, String fieldName, String fieldValueTextRepresentation) {
try {
Field field = User.class.getDeclaredField(fieldName);
Object fieldValue = null;
Class clazz = field.getType();
// Handle each class type: probably this code can be improved, but it is extensible and adaptable,
// you can include as many cases as you need.
if (clazz.isAssignableFrom(String.class)) {
fieldValue = fieldValueTextRepresentation;
} else if (clazz.isAssignableFrom(LocalDate.class)) {
// Adjust the date pattern as required
// For example, if you are receiving the information
// like this: year-month-day, as in the provided example,
// you can use the following pattern
fieldValue = LocalDate.parse(fieldValueTextRepresentation, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
} else if (clazz.isAssignableFrom(Integer.class)) {
fieldValue = Integer.parseInt(fieldValueTextRepresentation);
}
field.setAccessible(true);
field.set(user, fieldValue);
} catch (Exception e) {
// Handle the problem as appropriate
e.printStackTrace();
}
}

/* Look for Jackson aliases */
private Map<String, String> getAliases() {
Map<String, String> fieldAliases = new HashMap<>();

Field[] fields = User.class.getDeclaredFields();
for (Field field: fields) {
Annotation annotation = field.getAnnotation(JsonAlias.class);
if (annotation != null) {
String fieldName = field.getName();
JsonAlias jsonAliasAnnotation = (JsonAlias) annotation;
String[] aliases = jsonAliasAnnotation.value();
for (String alias: aliases) {
fieldAliases.put(alias, fieldName);
}
}
}

return fieldAliases;
}
}
有了此序列化程序后,给出了一个类似于User的类:
import java.time.LocalDate;

import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

@JsonDeserialize(using = UserDeserializer.class)
public class User {
private String firstName;
private String lastName;
private Integer age;
private String address;
@JsonAlias("dateofbirth")
private LocalDate dateOfBirth;

// Setters and getters omitted for brevity

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;

User user = (User) o;

if (firstName != null ? !firstName.equals(user.firstName) : user.firstName != null) return false;
if (lastName != null ? !lastName.equals(user.lastName) : user.lastName != null) return false;
if (age != null ? !age.equals(user.age) : user.age != null) return false;
if (address != null ? !address.equals(user.address) : user.address != null) return false;
return dateOfBirth != null ? dateOfBirth.equals(user.dateOfBirth) : user.dateOfBirth == null;
}

@Override
public int hashCode() {
int result = firstName != null ? firstName.hashCode() : 0;
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
result = 31 * result + (age != null ? age.hashCode() : 0);
result = 31 * result + (address != null ? address.hashCode() : 0);
result = 31 * result + (dateOfBirth != null ? dateOfBirth.hashCode() : 0);
return result;
}
以及以下JSON(我仅为了测试别名而更改为dateofbirth字段的名称):
{"firstName":"John","age":40,"dateofbirth":"1978-03-16"}
您应该获得适当的结果,请考虑以下测试:
  public static void main(String... args) throws JsonProcessingException {
User user = new User();
user.setFirstName("John");
user.setAge(40);
user.setDateOfBirth(LocalDate.of(1978, Month.MARCH, 16));

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

String json = "{\"firstName\":\"John\",\"age\":40,\"dateofbirth\":\"1978-03-16\"}";

User reconstructed = mapper.readValue(json, User.class);

System.out.println(user.equals(reconstructed));
}
最后,请注意,为了允许您的@KafkaListener处理null值,您必须将@Payload批注与required = false结合使用,例如:
public class KafkaConsumer {

@Autowired
private UserRepository userRepository;

@KafkaListener(topics = "${spring.kafka.topic.name}")
public void listen(@Payload(required = false) User user) {
// Handle null value
if (user == null) {
// Consider logging the event
// logger.debug("Null message received");
System.out.println("Null message received");
return;
}

// Continue as usual
User user = new User(user);
UserRepository.save(user.getName(), user);
}
}
请参阅相关的Spring Kafka documentation和此Github issue以及相关的commitThis SO question也可能是相关的。

关于java - JsonDeserializer不适用于该类,而仅适用于该类的单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66597864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com