0

I have json data like below:

{
  "data":[
    {"val":"1"},
    {"val":"2"},
    {"val":"3"}
  ]
}

But I am expecting something like this

{
  "data":[
    {"val":"Red"},
    {"val":"Green"},
    {"val":"Blue"}
  ]
}


@Column(name = "colorname")
@JsonProperty("val")
String colorName;

Is there any Jackson annotation that maps these numbers to colorNames while converting to Pojos? Or what could be the better way to get the expected result?

Rahbee Alvee
  • 1,924
  • 7
  • 26
  • 42
  • 1
    For this purpose, you need to define your custom serializer. please have a look at http://stackoverflow.com/questions/34297506/how-can-i-serialiize-deserialize-a-boolean-value-from-fasterxml-jackson-as-an-in – Manish Singh Nov 09 '16 at 05:32
  • 1
    use custom deserializer or customize setColorName() method – Derrick Nov 09 '16 at 06:19

1 Answers1

1

You could create an Ordinal Enum just like next:

public enum Color {
    Green, 
    Blue,
    Red
    //and so on
}

Then you would need a custom deserializer, you just need to do something like the next (specifying field name to the key and writeString to the color value):

public class ColorSerializer extends StdSerializer<Color> {

    public ColorSerializer() {
        this(null);
    }

    public ColorSerializer(Class<Color> t) {
        super(t);
    }

    public void serialize(Color value, JsonGenerator gen, SerializerProvider provider) 
      throws IOException, JsonProcessingException {
        gen.writeStartObject();
        gen.writeFieldName("val");
        gen.writeString(value.toString());
        gen.writeEndObject();
    }
} 

You must specify to use this serializer to your enum using annotation @JsonSerialize above Color enum as next:

@JsonSerialize(using = ColorSerializer.class)
public enum Color {
     //....
}

Finally, you must change your typecolorName property to Color enum type instead of String and annotate as Enumarted Ordinal type (JPA)

@Enumerated(EnumType.ORDINAL)
Color color;
Pau
  • 14,917
  • 14
  • 67
  • 94