简体   繁体   中英

Two questions about JsonProperty

Question 1:
Are

class Point {
    private int x;
    private int y;
    @JsonCreator
    public Point(@JsonProperty("x") int x, @JsonProperty("y") int y) {
        this.x = x;
        this.y = y;
    }
}

and

class Point {
    @JsonProperty("x")
    private int x;
    @JsonProperty("y")
    private int y;
    @JsonCreator
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

equivalent?

Question 2:
If I have a field that is not appeared in the parameters of the constructor, like:

class Point {
    private int x;
    private int y;
    private int z;
    @JsonCreator
    public Point(@JsonProperty("x") int x, @JsonProperty("y") int y) {
        this.x = x;
        this.y = y;
        z = 0;
    }
}

does Jackson still know about that field (z) and its value?

In order to serialize/deserialize classes with private fields and no formal getters/setters, I had to do the following:

mapper.enable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS);
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

and also define a private default constructor for my classes, like this:

public class ElementDesc {
  @SuppressWarnings("unused")
  private ElementDesc() { this(null, null, false); }

  public ElementDesc(/* a regular constructor with parameters etc */) {
    ...
  }

  private final String field1;
  private final String field2;
  private final boolean field3;
}

in this case Jackson can successfully serialize/deserialize instances of the class w/o need to use its regular constructor and (accessor) methods (if any).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM