1

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?

Hodor
  • 13
  • 2
  • You can use [Bean Validation](https://www.baeldung.com/javax-validation) or [Spring Validation](https://docs.spring.io/spring/docs/4.1.x/spring-framework-reference/html/validation.html#validation-beanvalidation) with custom constraints. Take a look at: [@Valid when creating objects with jackson without controller](https://stackoverflow.com/questions/55457754/valid-when-creating-objects-with-jackson-without-controller), [Spring MVC: How to perform validation?](https://stackoverflow.com/questions/12146298/spring-mvc-how-to-perform-validation) – Michał Ziober Mar 11 '20 at 06:36
  • @MichałZiober yeah I'm aware, that is what "@ValidColor" can do. But even if I do that, it will just validate the incoming string - good or bad - it won't convert it into a Color structure. – Hodor Mar 14 '20 at 11:26
  • To convert types you can use `Converter` interface. Take a look on this example: [Jackson deserialize JSON object field into single list property](https://stackoverflow.com/questions/18708533/jackson-deserialize-json-object-field-into-single-list-property) – Michał Ziober Mar 14 '20 at 12:45
  • @MichałZiober great that is what I was looking for! Post it as an answer and I'll mark it as the correct one. – Hodor Mar 14 '20 at 15:05

2 Answers2

0

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.

Shintaro Nomiya
  • 85
  • 1
  • 11
  • That wouldn't help anyway - there still need to be a custom conversion between the incoming string and the color. Either way the data is editable at runtime, so I can't use enum as well – Hodor Mar 14 '20 at 11:24
0

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

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146