0

The request model of the REST API has one enum field:

public enum CommentContext {  
  STUDENT_FEEDBACK,
  STUDENT_QUESTION;
}

Now I want to remove the STUDENT_ prefix from the enum value, but without breaking existing callers of the API.

I tried to use @JsonAlias, like this:

public enum CommentContext {
   @JsonAlias ("{FEEDBACK, STUDENT_FEEDBACK}")
   FEEDBACK,
   @JsonAlias ("{QUESTION, STUDENT_QUESTION}")
   COMMENT;
}

But the API is failing with 400 Bad Request, when STUDENT_FEEDBACK is passed as the value of that enum field in the request JSON.

Is it possible to deserialize this CommentContext object from JSON for either of the alternative values of this enum field such as FEEDBACK or STUDENT_FEEDBACK?

amy
  • 257
  • 1
  • 3
  • 10
  • Is this one similar to your requirement: https://stackoverflow.com/questions/9300191/how-to-annotate-enum-fields-for-deserialization-using-jackson-json#9314955 ? :) – Tianhao Wang Jul 24 '18 at 22:45

1 Answers1

0

You can do it using @JsonCreator. Here i gave solution for your problem:

public enum CommentContext {
STUDENT_FEEDBACK,
STUDENT_QUESTION;

@JsonCreator
public static CommentContext setValue(String key){
    Optional<CommentContext> commentContext = Arrays.stream(CommentContext.values())
            .parallel()
            .filter(ct -> ct.toString().equals(key) || ct.toString().substring(8).equals(key))
            .findAny();
    return commentContext.orElse(null);
}
}

you can also see this link

GolamMazid Sajib
  • 8,698
  • 6
  • 21
  • 39