Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Jackson使用基元类型数组反序列化包装器类_Java_Jackson - Fatal编程技术网

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

Java Jackson使用基元类型数组反序列化包装器类,java,jackson,Java,Jackson,我有一个类,如下所示,包装字节数组: 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);

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

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]}

作为代理人。然而,我不知道如何注释
计划
来实现这一点。如果它只是
byte[]
,就不会有问题,因为这将直接对应于代理中的一个命名属性,该属性可以作为
@JsonProperty(“plan”)
,但我需要告诉Jackson如何将数组包装到
plan
对象中。如何做到这一点?它真的需要自定义序列化程序吗?

您可以使用
@JsonCreator
注释第二个构造函数,指定要作为
字节
数组参数发送的JSON字段的名称:

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

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

尝试将
@JsonValue
放在
计划
类的
字节
-getter上。它将告诉Jackson应该仅使用该值序列化该类。此外,还需要指定创建者,如下所示

像这样:

class Plan {


  // ...

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

  @JsonValue
  public byte[] getBytes() {
      return bytes;
  }

  // ...

}

关于这一点似乎不起作用-我没有找到类ch.ethz.systems.nqsim.Plan的
序列化程序,也没有发现创建BeanSerializer的属性
@MichelMüller在我的测试中工作过。你有合适的getter和setter bean吗?我在这里试图避免setter,所以这可能就是问题所在。我已经添加了一个提示,说明还需要构造函数。谢谢大家!
@JsonValue
确实是我所缺少的。啊,是的。反序列化需要
@JsonCreator