代码之家  ›  专栏  ›  技术社区  ›  Michel Müller

Jackson使用基元类型数组反序列化包装类

  •  2
  • Michel Müller  · 技术社区  · 6 年前

    我有一个类,如下所示,包装字节数组:

    public final class Plan {
      private byte[] bytes;
      private int peekIdx;
    
      public Plan(byte[] bytes, int peekIdx) {
          this.bytes = bytes;
          this.peekIdx = peekIdx;
      }
    
      public Plan(byte[] bytes) {
          this(bytes, 0);
      }
    
      //bunch more methods
    }
    

    它包含在其他对象中

    public final class Agent {
         private Plan plan;
         //bunch more properties...
    }
    

    现在我想反序列化一个类似JSON的

    {"plan": [0, 1, 2]}
    

    作为代理人。但是我不知道如何注释 Plan 为了达到这个目的。如果只是 byte[] 不会有问题,因为这将直接对应于代理中的命名属性,该属性可以作为 @JsonProperty("plan") 但我想告诉杰克逊如何将数组包装在 计划 对象。如何做到这一点?它真的需要自定义序列化程序吗?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Michel Müller    6 年前

    试放 @JsonValue bytes -吸气器 Plan 班级。它将告诉Jackson类应该只使用该值序列化。此外,还需要如下指定创建者。

    这样地:

    class Plan {
    
    
      // ...
    
      @JsonCreator
      public Plan(byte[] bytes) {
        this(bytes, 0);
      }
    
      @JsonValue
      public byte[] getBytes() {
          return bytes;
      }
    
      // ...
    
    }
    
        2
  •  0
  •   ernest_k Petronella    6 年前

    您可以使用 @JsonCreator ,指定要作为 byte 数组参数:

    @JsonCreator
    public Plan(@JsonProperty("plan") byte[] bytes) {
        this(bytes, 0);
    }
    

    这会告诉Jackson使用这个构造函数,并向它发送 plan JSON对象的字段。