Issue
I'm using spring web with controllers services models and validation. I have a Color object and a Color service.
@Data
public class Color {
private String name;
private long value;
private int rating;
}
In one of my controllers, I'm accepting an object:
public class NewEventRequest {
@NotNull
@Size(min = 5, max = 30)
private String eventName;
/* @ValidColor */
private Color eventColor;
// private String eventColor;
}
As you can see, the eventColor
sub-property is of type Color
. However, I want the sender to be able to send just the color name (there aren't many colors and they're cached in memory anyway).
I know I can use a color of type string and validators to make sure that color exist, but is there a way to also then cast it to Color?
Solution
If JSON
payload does not fit Java
model you need to implement custom deserialiser or Converter interface. Take a look at this example:
Answered By - MichaĆ Ziober
Answer Checked By - David Marino (JavaFixing Volunteer)