0

I'm trying to force gson to throw an exception when an string does not map to an object which I'm passing to it.

@ResponseStatus(HttpStatus.CREATED)
@PostMapping("offer")
public String postOffer(@RequestBody String jsonBody) {
    Offer offer = gson.fromJson(jsonBody, Offer.class);
    offerRepository.save(offer);
    return offer.getId();
}

Currently, it will just save what ever it can to the db and ignore any elements that don't map to the class. This is bad for me because I get bad data making it's way to the db.

Any help would be appreciated.

ps. using springboot-data-mongodb and gson for mapping.

Thanks

Kaigo
  • 1,267
  • 2
  • 14
  • 33

2 Answers2

0

In GSON you cannot make some fields required. You can handle this i your code, if the variable is not present in json then in Offer object that variable will simple be assigned as null. You can add null check to your code for the required fields and throw your own exception.

Since gson dont have this facility, you can also try the answer from below link- Gson optional and required fields

batflix
  • 196
  • 5
0

To achieve this you need to follow two steps:-
1) Mark all required field in Offer class as @NotNull(message="your custom message")
2) Add below class to tell Mongo to validate document before persisting it to the database.

@Configuration
public class MongoEventValidationListener {

  @Bean
  public ValidatingMongoEventListener validatingMongoEventListener() {

    return new ValidatingMongoEventListener(validator());
  }

  @Bean
  public LocalValidatorFactoryBean validator() {

    return new LocalValidatorFactoryBean();
  }
}
Nishant Bhardwaz
  • 924
  • 8
  • 21