Reputation: 319
I'm having some difficulty in translating a certain Java Enum to JSON. I have the following Enum:
public enum Color {
BLUE("Blue"), RED("Red");
private String colorName;
Color(final String colorName) {
this.colorName = colorName;
}
@Override
public String toString() {
return colorName;
}
}
When converting to JSON, I'd like to use the name, so I've overridden the toString method. I thought that was enough, but when I do this test:
Gson gson = new Gson();
assertEquals("Blue", gson.toJson(Color.BLUE));
It fails! It gives me "BLUE"... is there any way I can make the thing return "Blue"?
I've also tried the @JsonValue annotation on a method that returns the name but to no result. The fasterxml @JsonFormat also give me nothing...
Upvotes: 1
Views: 1294
Reputation: 319
I found the solution myself, but StaxMan made me persist in trying :)
What I did was adding an annotation from Jackson 2.x, but in my tests I used Gson to convert to json. These don't play together. So when you're using Jackson to define the json output, also use Jackson to convert your object to json:
public class ColorTest {
@Test
public void convertToJson() throws JsonProcessingException {
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(Colors.BLUE);
assertEquals("\"blue\"", json);
}
private enum Colors {
RED("red"), BLUE("blue");
private String colorName;
Colors(final String colorName) {
this.colorName = colorName;
}
@JsonValue
@Override
public String toString() {
return colorName;
}
}
}
Works like a charm!
Upvotes: 2
Reputation: 116620
@JsonValue
on method that returns name to use does work. Just make sure that you are not accidentally using wrong Jackson annotations (Jackson 2.x requires annotations from com.fasterxml.jackson.annotation
; Jackson 1.x ones from org.codehaus.jackson
). Also, if you are using an old Jackson version, try upgrade; support for @JsonValue
was added somewhere around 2.4 I think.
Upvotes: 1
Reputation: 575
first of all, even if it's not the cause avoid naming the attribut name.
otherwise, change your code like this and it will work.
public enum Color {
@SerializedName("Blue") BLUE("Blue"),
@SerializedName("Red") RED("Red");
private String name;
Color(final String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
Upvotes: 1