Java Spring web - convert sub-property to object with validator

189 Views Asked by At

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?

2

There are 2 best solutions below

0
Michał Ziober On BEST ANSWER

If JSON payload does not fit Java model you need to implement custom deserialiser or Converter interface. Take a look at this example:

1
Shintaro Nomiya On

Why don't you use Enum types instead of string? like as:

public enum ColorName {
    Red, Yellow, Blue, ...
}

@Data
public class Color {
    private ColorName name;
    private long value;
    private int rating;
}

I don't know whether I understand what you mean correctly, but it could contain values Only you defined. So you don't even need to validate the values.