Skip to content
Advertisement

Post request transform int field to string automatically

I’m doing a dummy app of a hostpital. The problem I’m having is that, I’m trying to verify that when a Patient is created, the fields passed are of the correct type, but whenever I POST an Int in a String field, it doesn’t fail and just transform the Int to String. The field I’m trying to make fail is “surname”, which by the definition of the Patient class, is a String.

If I do this (I pass a number to the “surname” field):

{
    "name": "John",
    "surname": 43,
    "sickness": "headache"
}

It just transforms 43 into a String by the time its in the Controller method. enter image description here

Here we have the Patient object:

@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
public class Patient implements Serializable {

    private static final long serialVersionUID = 4518011202924886996L;

    @Id
    //TODO: posible cambiar luego la generationType
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "patient_id")
    private Long id;

    @Column(name = "patient_name")
    @JsonProperty(required = true)
    private String name;

    @Column(name = "patient_surname")
    @JsonProperty(required = true)
    private String surname;

    @Column(name = "patient_sickness")
    @JsonProperty(required = true)
    private String sickness;
}

And this is the controller class:

@Controller
@Path("/patient")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public class PatientController {

    @POST
    @Path("")
    public ResponseEntity<Object> postPatient(final Patient patient) {
        ResponseEntity<Object> createdPatient = patientBusiness.createPatient(patient);
        return new ResponseEntity<Patient>(createdPatient.getBody(), createdPatient.getStatusCode());
    }

EDIT 1:

Following the “clues” and closing the circle of attention, I tried modifying the ObjectMapper, but my configuration isn’t applying. I’m still getting the error from above.

This is the config class:

@Configuration
public class JacksonConfig {

    @Bean
    @Primary
    public ObjectMapper getModifiedObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);
        mapper.coercionConfigFor(LogicalType.Integer).setCoercion(CoercionInputShape.String, CoercionAction.Fail);

        return mapper;
    }
}

Even added the property to the application.yml, but still nothing:

spring:
    jackson:
        mapper:
            allow-coercion-of-scalars: false

Any help is appreciated. Thx.

Advertisement

Answer

In the end I referred to this post to do a deserializer and a module to just have it along all the program, not just the field I want not to be transformed.

Disable conversion of scalars to strings when deserializing with Jackson

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement