这里的法典
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.ToString;
public class Main {
public static void main(String[] args) throws Exception {
Fields f1 = new Fields(1);
System.out.println(f1);
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(f1);
System.out.println(str);
Fields f2 = mapper.readValue(str, Fields.class);
System.out.println(f2);
}
@Data
@ToString
public static class Fields {
private final long value1;
private final long value2;
public Fields(@JsonProperty("blah") long value) {
this.value1 = value++;
this.value2 = value++;
System.out.println(this);
}
}
}
产出
Main.Fields(value1=1, value2=2)
Main.Fields(value1=1, value2=2)
{"value1":1,"value2":2}
Main.Fields(value1=0, value2=1)
Main.Fields(value1=1, value2=2)
我的问题是:
- Why did jackson modify private final fields that do not have setters after finish constructing it? If this is intended, how do I turn it off?
- If jackson is able to set fields directly, why is it required that I annotate the constructor with @JsonProperty? (Removing @JsonProperty from Fields results in error; and I didn t even need to annotate with correct properties)
谢谢。