且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在RestController中使用基于JsonView的两个不同的getter进行序列化?

更新时间:2023-01-15 11:39:20

您可以尝试为对象映射器定义自定义序列化器,这样,只要 object mapper 用于序列化时,您可以检查密码和信用卡字段并将其转换为您选择的值.例如

You can try defining a custom serializer for the object mapper , so that whenever the object mapper is used for serialization you can check and convert the password and credit card field to the value you choose.For example

public class ItemSerializer extends StdSerializer<Item> {

    public ItemSerializer() {
        this(null);
    }

    public ItemSerializer(Class<Item> t) {
        super(t);
    }

    @Override
    public void serialize(
      Item value, JsonGenerator jgen, SerializerProvider provider) 
      throws IOException, JsonProcessingException {

        jgen.writeStartObject();
        jgen.writeNumberField("id", value.id);
        jgen.writeStringField("itemName", value.itemName);
        jgen.writeNumberField("owner", value.owner.id);
        jgen.writeEndObject();
    }
}

您可以提供一个使用该自定义序列化程序的对象映射器,

You can provide an object mapper that utilizes this custom serializer then,

Item myItem = new Item(1, "theItem", new User(2, "theUser"));
ObjectMapper mapper = new ObjectMapper();

SimpleModule module = new SimpleModule();
module.addSerializer(Item.class, new ItemSerializer());
mapper.registerModule(module);

String serialized = mapper.writeValueAsString(myItem);

在这种情况下,您可以在spring上下文中向自定义序列化器注册objectmapper bean,并使jackson使用您的对象映射器bean.

In your case you can register the objectmapper bean with the custom serializer in the spring context and make jackson use your object mapper bean.

或使用@JsonSerialize注释,如:

public class Event {
    public String name;

    @JsonSerialize(using = CustomDateSerializer.class)
    public Date eventDate;
}


Public class CustomDateSerializer extends StdSerializer<Date> {

    private static SimpleDateFormat formatter 
      = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");

    public CustomDateSerializer() { 
        this(null); 
    } 

    public CustomDateSerializer(Class<Date> t) {
        super(t); 
    }

    @Override
    public void serialize(
      Date value, JsonGenerator gen, SerializerProvider arg2) 
      throws IOException, JsonProcessingException {
        gen.writeString(formatter.format(value));
    }
}

引用:

https://www.baeldung.com/jackson-json-view-annotation

https://www.baeldung.com/jackson-custom-serialization