2

I am trying to create a standard way to serialize and deserialize for Enum on Jackson.

My serialize is easy:

public class EnumSerializer extends JsonSerializer<Enum<?>> {

    @Override
    public void serialize(Enum<?> data, JsonGenerator gen, SerializerProvider provider)
            throws IOException, JsonProcessingException {

        if (data == null) {
            gen.writeString("");
        } else {
            gen.writeString(data.name());
        }
    }
}

Now I am working on Deserializer:

public class EnumDeserializer extends JsonDeserializer<Enum<?>> {

    @Override
    public Enum<?> deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext)
            throws IOException, JsonProcessingException {

        String dataStr = jsonparser.getText();
        if (dataStr == null || dataStr.isEmpty()) {
            return null;
        } else {
            Class<Enum<?>> enumClass = null;   // How can I get enumClass?
            for(Enum<?> one: enumClass.getEnumConstants()){
                if(one.name().equals(dataStr)){
                    return one;
                }
            }
            return null;
        }
    }
}

But you can see I have trouble to get enumClass.

Could you please help me?

Thanks!

shmosel
  • 49,289
  • 6
  • 73
  • 138
Justin
  • 1,050
  • 11
  • 26
  • What is the problem with `Enum.class`? – m0skit0 Nov 06 '17 at 23:13
  • 1
    You didn't save any information about the class when you were serializing the data, so you'll have to determine the class from somewhere other than the serialized data. Probably a constructor argument. – user2357112 Nov 06 '17 at 23:16
  • 1
    Assuming you can get the class, there's a much simpler way of getting the constant: `Enum.valueOf(enumClass, dataStr)` – shmosel Nov 06 '17 at 23:18
  • 1
    I don't see what this question has to do with generics. – shmosel Nov 06 '17 at 23:18
  • Sometimes it is much cleaner and better not to be lazy and write serializer/deserializer for each enum type. If you want to have generic deserializer then you must pass enum class to it, that is almost impossible to do given the fact that `@JsonDeserialize` annotation does not take parameter. Check out this one on how it is creating contextual JsonSerializer, maybe it can lead you to the right direction: https://stackoverflow.com/questions/22634860/how-to-pass-parameter-to-jsonserializer – tsolakp Nov 06 '17 at 23:27

1 Answers1

2

If you really want to create the custom EnumDeserializer you can see the implementation of Jackson: com.fasterxml.jackson.databind.deser.std.EnumDeserializer

But as I can see you try to implement the standard behavior of Jackson.

sergey
  • 368
  • 2
  • 7
  • Thanks, I knew Jackson has default implementation to match my requirement. My real case is not on Jackson, it is on another Json tool, it is hard to bring all code here, so I just borrow Jackson as a sample. – Justin Nov 13 '17 at 18:46