javajacksonmixinsobjectmapper

How to override @JsonProperty(value = "id", access = JsonProperty.Access.READ_ONLY) on object mapper


I've a model class which I can't change its source, it is annotated with

public class Announce {

   @JsonProperty(value = "id", access = JsonProperty.Access.READ_ONLY)
   @Id
   @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "announce_sequence")
   @SequenceGenerator(name = "announce_sequence", sequenceName = "announce_id_sequence", allocationSize = 100)
   @Setter(AccessLevel.NONE)
   private Long id;
}

Due that access = JsonProperty.Access.READ_ONLY ObjectMapper won't deserialize the id that comes in the json response I get.

Is there a way to force it ignore JUST THAT ANNOTATION [override it]?

my status:

Does anyone have any idea what I can do?

anyone with real experience with mixIn can tell me they should work?


Solution

  • I'm still hopping someone can teach me how to do that with mixIns or some small tweaks in the ObjectMapper configurations but I'm posting my current solution so other people can have an idea

    @Configuration
    public class ObjectMapperConfiguration {
       @SneakyThrows
       @Autowired
       public void configureObjectMapper(@NonNull final ObjectMapper objectMapper) {
          objectMapper.registerModule(new SimpleModule().addDeserializer(Announce.class, new JsonDeserializer<Announce>() {
             private final Field field = Announce.class.getDeclaredField("id");
    
             @Override
             public Announce deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
                final InnerAnnounce result = objectMapper.readValue(p, InnerAnnounce.class);
                ReflectionUtils.setField(field, result, result.innerId);
                return result;
             }
          }));
       }
    
    
       @Setter
       private static final class InnerAnnounce extends Announce {
          @JsonAlias({"id"})
          private Long innerId;
       }
    }
    

    The origial ObjectMapper bean is crated in another class so i get it, add a new deserializer that will deserialize into a child class, which was custom made to have the minimum possible modifications, and later I set the extra field by reflection

    It is a really small workaround but I not a fan of using reflection in my own code like this