如何在 Spring Boot ObjectMapper 中排除带有自定义注释的字段

发布于 2025-01-09 19:49:09 字数 1133 浏览 1 评论 0原文

我需要在应用程序中拥有两个不同的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) 打印:

{"name": ""student1", 年龄: 10, "grade": "A+"}

customObjectMapper.writeValuesAsString(someStudent) 打印:

{"name": ""student1", 年龄: 10}

I have a need to have two different ObjectMapper in the application.

Pojo I am working with:

public class Student {

 private String name;
 private Integer age;

 @HideThisField
 private String grade; 

 // getters & setters..
}

One is the out of the box configuration based ObjectMapper as below:

@Bean("objectMapper")
public ObjectMapper getRegularObjectMapper() {
     //With some configurations 
     return new ObjectMapper();
}

I need another ObjectMapper that while serializing ignores a few fields for all objects based on an annotation on a field.

@Bean("customObjectMapper")
public ObjectMapper getCustomObjectMapper() {
   // This is where i want to ignore the fields with @HideThisField
   return new ObjectMapper();
}

Output of the two mappers:

objectMapper.writeValuesAsString(someStudent) prints:

{"name": ""student1", age: 10, "grade": "A+"}

customObjectMapper.writeValuesAsString(someStudent) prints:

{"name": ""student1", age: 10}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天冷不及心凉 2025-01-16 19:49:09

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 块中.

JacksonAnnotationIntrospector handles standard Jackson annotations. Overriding the hasIgnoreMarker method, you can make it work according to your own annotation.

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 {}

The console output is:

{"name":"Student 1","age":10,"grade":"A+"}
{"name":"Student 1","age":10}

getCustomObjectMapper() don't skips JsonIgnore annotations because you override the standard, if you want, you need to add this to the if block.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文