In a JEE application, I created an enumeration with some custom label strings for the GUI:
public enum MyThing
{
THING1("Label 1"),
...
THING5("Label 5");
private String label;
private MyThing(String label)
{
this.label = label;
}
...
}
Objects with attributes of this enum type get delivered over a REST API. The attribute values get serialized as string IDs, wich is what I need:
Class with enum attribute:
public class MyBO
{
private MyThing thing;
...
}
Service class:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
...
@Path("/bos")
public class MyBOsService
{
@GET
@Produces(MediaType.APPLICATION_JSON)
public BO getBO()
{
BO bo = new BO();
...
return bo;
}
}
REST call result:
{"thing":"THING1",...}
Great! Now, however, I'd like to also deliver a complete list of IDs and labels through a different REST service class:
@Path("/masterdata")
public class MasterDataService
{
@GET
@Produces(MediaType.APPLICATION_JSON)
public MyThing[] allMyThings()
{
return MyThing.values();
}
}
Desired REST call result:
[{"THING1":"Label 1"},{"THING2":"Label 2"}, ...]
I created a custom Jackson JsonSerializer to serialize the enum values as id-label pairs:
import org.codehaus.jackson.map.JsonSerializer;
...
public class MyThingSerializer extends JsonSerializer<MyThing>
{
@Override
public void serialize(MyThing myThing, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException
{
...
}
}
But now, I cannot find a sensible place to attach this JsonSerializer through an @JsonSerialize annotation. If I attach it to the enum like
@JsonSerialize(using = MyThingSerializer.class)
public enum MyThing{...
all enum values get serialized as id-label pairs, which is wrong for all REST calls but one.
If I attach it to the method supposed to deliver the list of id-value pairs, nothing happens:
@Path("/masterdata")
public class MasterDataService
{
@GET
@Produces(MediaType.APPLICATION_JSON)
@JsonSerialize(using = MyThingSerializer.class)
public MyThing[] allMyThings()
{
return MyThing.values();
}
}
REST call result:
["THING1","THING2",...]
I know that I could attach the "id-label serializer" to the enum itself and then attach another serializer that restores the default serialization again to all other occurences of the enum, but is there a smarter way to achieve the desired different serializations in the different spots?