Câu trả lời được chấp nhận sẽ không phù hợp với trường hợp của tôi.
Trong trường hợp của tôi, lớp học không thuộc sở hữu của tôi. Lớp có vấn đề đến từ các phụ thuộc của bên thứ 3, vì vậy tôi không thể chỉ thêm @JsonPropertychú thích trong đó.
Để giải quyết vấn đề này, lấy cảm hứng từ câu trả lời @burak ở trên, tôi đã tạo một tùy chỉnh PropertyNamingStrategynhư sau:
mapper.setPropertyNamingStrategy(new PropertyNamingStrategy() {
@Override
public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName)
{
if (method.getParameterCount() == 1 &&
(method.getRawParameterType(0) == Boolean.class || method.getRawParameterType(0) == boolean.class) &&
method.getName().startsWith("set")) {
Class<?> containingClass = method.getDeclaringClass();
String potentialFieldName = "is" + method.getName().substring(3);
try {
containingClass.getDeclaredField(potentialFieldName);
return potentialFieldName;
} catch (NoSuchFieldException e) {
}
}
return super.nameForSetterMethod(config, method, defaultName);
}
@Override
public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName)
{
if(method.hasReturnType() && (method.getRawReturnType() == Boolean.class || method.getRawReturnType() == boolean.class)
&& method.getName().startsWith("is")) {
Class<?> containingClass = method.getDeclaringClass();
String potentialFieldName = method.getName();
try {
containingClass.getDeclaredField(potentialFieldName);
return potentialFieldName;
} catch (NoSuchFieldException e) {
}
}
return super.nameForGetterMethod(config, method, defaultName);
}
});
Về cơ bản điều này làm là, trước khi tuần tự hóa và giải mã hóa, nó sẽ kiểm tra trong lớp đích / nguồn tên thuộc tính nào hiện diện trong lớp, cho dù đó là thuộc tính isEnabledhay thuộc enabledtính.
Dựa vào đó, trình ánh xạ sẽ tuần tự hóa và giải mã hóa thành tên thuộc tính đang tồn tại.
isSuccesstên phương thức phải làisIsSuccesstôi nghĩ