-1

I have some entry points with JAXRS and jackson serialization/deserialization, but for some values we want to capitalize it as WordUtils.capitalizeFully(str, ' ', '-') i am using lombok and jackson 2.9.8

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@Getter @Setter
Class User{

   @Column(length = 100, nullable = true)
   @Size(max = 100, message = "USER_FIRSTNAME_SIZE")
   private String firstName;

   @Column(length = 100, nullable = true)
   @Size(max = 100, message = "USER_LASTNAME_SIZE")
   private String lastName;

}

When I insert a user for example:

{"lastName":"smith-test","firstname":"john"}

i want to save "Smith-Test John", I am using annotations so i don't know how to proceed, before we had manual insert with JsonObject, but now we're passing in full jackson and automatic mapping

cyril
  • 872
  • 6
  • 29

1 Answers1

2

You could simply implement setters and perform conversion there. Alternatively you can use custom deserializer:

public class CustomDeserializer extends StdDeserializer<String> {

    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext
            deserializationContext) throws IOException, JsonProcessingException {
        return WordUtils.capitalizeFully(jsonParser.getText(),'  ', '-') ;
    }
}

and then assign it to the field:

@JsonDeserialize(using = CustomDeserializer.class)
private String lastName;

EDIT

Sorry, it seems I misunderstood the question, you need rather a serializer. The approach is the same, but you will need to implement StdSerializer<String> and use @JsonSerialize annotation.

public class CustomSerializer extends StdSerializer<String> {

    public CustomSerializer(Class t) {
        super(t);
    }

    @Override
    public void serialize(String str, JsonGenerator jgen, SerializerProvider sp) throws IOException, JsonGenerationException {

        jgen.writeString(WordUtils.capitalizeFully(str, ' ', '-'));
    }
}
Mafor
  • 9,668
  • 2
  • 21
  • 36
  • hello, i made exactly this on my side but on class i put annotation like that i can manage all fields in one time – cyril Dec 27 '19 at 21:10