[EN] Simple @JsonbCreator example

Here is a simple scenario;  I will call a rest URL with POST with curl and system will create the entity object on the fly.

curl -H 'Content-Type:application/json' -d '{"number":23, "numberOfSeats":"23"}' -X POST http://localhost:8080/airport/resources/flights

Let’s start with the boundary layer

@Stateless
@Path("flights")
public class FlightsResource {
   @POST
   public void save(Flight flight) {
      this.coordinator.save(flight);
   }
}

Then controller layer

@ApplicationScoped
public class FlightCoordinator {

private ArrayList<Flight> list;

@PostConstruct
public void init() {
   this.list = new ArrayList<>();
   this.list.add(new Flight("lh42", 42));
}
public void save(Flight flight) {
   this.list.add(flight);
}

}

Entity class :

public class Flight {

   public String number;
   public int numberOfSeats;

   @JsonbCreator
   public Flight(@JsonbProperty("number") String number, @JsonbProperty("numberOfSeats") int    numberOfSeats) {
     this.number = number;
     this.numberOfSeats = numberOfSeats;
  }

}

@JsonbCreator  annotation will create the Flight object on the fly so that we will be able to insert Flight object into the database. Also by using @JsonbProperty annotation, you can change the variable names.

Thanks to Adam Bien for this example

No Comments

Post a Comment

Comment
Name
Email
Website