Jackson serialization for enum without quotes

Viewed 53

Could someone help me with the kind of configuration that i need to do for my ObjectWriter such that it produces, an enum value without quotes ?

Is this possible to do this without using a custom serializer for enum ? with simple configuration ?

Can i declare some annotations on top of my enums or some kind of configuration to my objectwriter such that, it always produces enum values without quotes ?

ObjectWriter.writeValueAsString(object) ---> This should write enum value without quotes.

1 Answers

For a one-off serialization you can do this in two steps.

  1. convert the enum to a TextNode
  2. get the text value of the text node

In the example below the CAT enum is printed with quotes, while DOG is printed without quotes.

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.TextNode;

public class WriteEnumAsString {

    public enum Animal {
        CAT,
        DOG,
    }

    public static void main(String[] args) throws JsonProcessingException {
        var om = new ObjectMapper();

        var catString = om.writeValueAsString(Animal.CAT);
        System.out.println(catString);
        // "CAT"

        TextNode dogNode = om.valueToTree(Animal.DOG);
        String dogString = dogNode.textValue();
        System.out.println(dogString);
        // DOG
    }
}
Related