Serializing enums with Jackson

后端 未结 7 1319
借酒劲吻你
借酒劲吻你 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:36
    @JsonFormat(shape= JsonFormat.Shape.OBJECT)
    public enum SomeEnum
    

    available since https://github.com/FasterXML/jackson-databind/issues/24

    just tested it works with version 2.1.2

    answer to TheZuck:

    I tried your example, got Json:

    {"events":[{"type":"ADMIN"}]}
    

    My code:

    @RequestMapping(value = "/getEvent") @ResponseBody
      public EventContainer getEvent() {
        EventContainer cont = new EventContainer();
        cont.setEvents(Event.values());
        return cont;
     }
    
    class EventContainer implements Serializable {
    
      private Event[] events;
    
      public Event[] getEvents() {
        return events;
     }
    
     public void setEvents(Event[] events) {
       this.events = events;
     }
    }
    

    and dependencies are:

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
      <exclusions>
        <exclusion>
          <artifactId>jackson-annotations</artifactId>
          <groupId>com.fasterxml.jackson.core</groupId>
        </exclusion>
        <exclusion>
          <artifactId>jackson-core</artifactId>
          <groupId>com.fasterxml.jackson.core</groupId>
        </exclusion>
      </exclusions>
    </dependency>
    
    <jackson.version>2.1.2</jackson.version>
    
    0 讨论(0)
提交回复
热议问题