我需要ObjectMapper在應用程式中有兩個不同的。
我正在與 Pojo 合作:
public class Student {
private String name;
private Integer age;
@HideThisField
private String grade;
// getters & setters..
}
一種是開箱即用的配置ObjectMapper,如下所示:
@Bean("objectMapper")
public ObjectMapper getRegularObjectMapper() {
//With some configurations
return new ObjectMapper();
}
我需要另一個ObjectMapper在序列化時忽略基于欄位注釋的所有物件的一些欄位。
@Bean("customObjectMapper")
public ObjectMapper getCustomObjectMapper() {
// This is where i want to ignore the fields with @HideThisField
return new ObjectMapper();
}
兩個映射器的輸出:
objectMapper.writeValuesAsString(someStudent)印刷:
{“姓名”:“學生1”,年齡:10,“年級”:“A ”}
customObjectMapper.writeValuesAsString(someStudent)印刷:
{“姓名”:“學生1”,年齡:10}
uj5u.com熱心網友回復:
JacksonAnnotationIntrospector處理標準Jackson注釋。覆寫該hasIgnoreMarker方法,您可以根據自己的注釋使其作業。
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.introspect.*;
import java.lang.annotation.*;
public class StudentExample {
public static void main(String[] args) throws JsonProcessingException {
Student student = new Student();
student.setName("Student 1");
student.setAge(10);
student.setGrade("A ");
String st1 = getRegularObjectMapper().writeValueAsString(student);
String st2 = getCustomObjectMapper().writeValueAsString(student);
System.out.println(st1);
System.out.println(st2);
}
public static ObjectMapper getRegularObjectMapper() {
return new ObjectMapper();
}
public static ObjectMapper getCustomObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
@Override
public boolean hasIgnoreMarker(AnnotatedMember m) {
if (_findAnnotation(m, HideThisField.class) != null)
return true;
return false;
}
});
return objectMapper;
}
}
class Student {
private String name;
private Integer age;
@HideThisField
private String grade;
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface HideThisField {}
控制臺輸出為:
{"name":"Student 1","age":10,"grade":"A "}
{"name":"Student 1","age":10}
getCustomObjectMapper()不要跳過JsonIgnore注釋,因為您覆寫了標準,如果需要,您需要將其添加到 if 塊中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/433088.html
