Serializing enums with Jackson

后端 未结 7 1368
借酒劲吻你
借酒劲吻你 2020-11-28 01:50

I have an Enum desrcibed below:

public enum OrderType {

  UNKNOWN(0, \"Undefined\"),
  TYPEA(1, \"Type A\"),
  TYPEB(2, \"Type B\"),
  TYPEC(3, \"Type C\");         


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 02:24

    An easy way to serialize Enum is using @JsonFormat annotation. @JsonFormat can configure the serialization of a Enum in three ways.

    @JsonFormat.Shape.STRING
    public Enum OrderType {...}
    

    uses OrderType::name as the serialization method. Serialization of OrderType.TypeA is “TYPEA”

    @JsonFormat.Shape.NUMBER
    Public Enum OrderTYpe{...}
    

    uses OrderType::ordinal as the serialization method. Serialization of OrderType.TypeA is 1

    @JsonFormat.Shape.OBJECT
    Public Enum OrderType{...}
    

    treats OrderType as a POJO. Serialization of OrderType.TypeA is {"id":1,"name":"Type A"}

    JsonFormat.Shape.OBJECT is what you need in your case.

    A little more complicated way is your solution, specifying a serializer for the Enum.

    Check out this reference: https://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonFormat.html

提交回复
热议问题