简体   繁体   中英

How to prevent ObjectMapper de-serializing plain string to Object successfully?

I have a simple POJO:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class StatusPojo {

  private String status;

}

When I de-serialize simple string "asd" (without quotes) like this:

StatusPojo pojo = new ObjectMapper().readValue("asd", StatusPojo.class)

I am getting a StatusPojo object created successfully, with status field's value as "asd", though it is not valid JSON and nowhere has the field name "status" mentioned along.

Why is it behaving like this and how to disable this behavior and have object mapper throw an exception?

Your POJO has @AllArgsConstructor (maybe because of the @Builder ) that then generates something like this:

public StatusPojo(String status) {
    this.status = status;
}

When ObjectMapper then de-serializes plain string it uses that constructor to create object.

If you added some other property to your pojo, like just:

private String noAsdPlease;

there would be an exception, because ObjectMapper could not find creator, there would not be that above mentioned constructor but with two String params.

At quick glace DeserializationFeature does not have such a feature that disables using one string arg constructor for plain string.

Playing with more fields, removing @Builder & @AllArgsConstructor might resolve your problem but if you cannot change those ther might not be other options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM