【问题标题】:JAVA - JSON Serialize a list of enum to a classJAVA - JSON 将枚举列表序列化为类
【发布时间】:2020-01-28 14:43:57
【问题描述】:

我有这个枚举:

public enum Days implements Serializable {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    ...
}

我想在 Store 类中使用它:

 public class Store{
      private integer id_store;
      private String name;
      private Days days_visit;
}

问题是,days_visit 需要是一个数组,因为它可以超过一天;在数据库端,Days类型是days类型:

CREATE TYPE schema.days AS ENUM
   (MONDAY,
    TUESDAY,
    WEDNESDAY,
    ...);

并且表 Stores 有一个“days”数组

days_visit schema.days[],

如何在 JSON 中序列化?我试过的 JSON 是:

{"id_store":"1", "name":"The Store", "days_visit":["MONDAY", "FRIDAY"]}

但我收到此错误:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of org.domain.Days
    out of START_ARRAY token
    at [Source: io.undertow.servlet.spec.ServletInputStreamImpl@5c2a7de1; line: 1, column: 168] (through reference chain:
    org.Stores["days_visit"])

如果我在课堂上这样声明 days_visit:

 public class Store{
      private integer id_store;
      private String name;
      private Days[] days_visit;
}

在 Wildfly 中部署时出现此错误:

[2020-01-28 11:42:09,970] Artifact app:war: Error during artifact deployment. See server log for details.
    [2020-01-28 11:42:09,970] Artifact app:war: java.lang.Exception: {"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"app.war#org\"" => "javax.persistence.PersistenceException: [PersistenceUnit: org_app] Unable to build Hibernate SessionFactory
        Caused by: javax.persistence.PersistenceException: [PersistenceUnit: org.app] Unable to build Hibernate SessionFactory
        Caused by: org.hibernate.MappingException: Unable to instantiate custom type: org.hibernate.type.EnumType
        Caused by: java.lang.ClassCastException: class [Lpy.org.app.domain.Days;"}}

我有什么遗漏吗?

【问题讨论】:

    标签: java json hibernate


    【解决方案1】:

    问题似乎在于反序列化 JSON。

    com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of org.domain.Days

    Jackson 无法反序列化枚举。你可以编写一个自定义的反序列化方法并用@JsonCreator注解它。

    根据您的要求/约束​​调整以下逻辑。

    public enum Days {
        MONDAY, TUESDAY, WEDNESDAY;
        static Map<String, Days> daysLookup = new HashMap<>();
    
        static {
            daysLookup.put("MONDAY", MONDAY);
            daysLookup.put("TUESDAY", TUESDAY);
            daysLookup.put("WEDNESDAY", WEDNESDAY);
        }
    
    
        @JsonCreator
        public static Days[] create(@JsonProperty("days_visit") String[] days) {
            Days[] daysVisit = new Days[days.length];
            for (int i = 0; i < days.length; i++) {
                daysVisit[i] = daysLookup.get(days[i]);
            }
            return daysVisit;
        }
    }
    

    【讨论】:

    • 如果你不想污染你的域名,你也可以使用MixIns来实现。
    猜你喜欢
    • 1970-01-01
    • 2013-09-01
    • 2014-08-20
    • 2013-01-24
    • 2013-09-04
    • 1970-01-01
    • 2018-10-11
    • 2018-06-21
    • 2017-04-10
    相关资源
    最近更新 更多