Using json to save and load data requires a constructor for json to load the object, and I'm having trouble getting lombok annotations to work with this. What should I do?
This is what my class looked like before and after attempting to use an annotation to construct my item:
@Data
public class Item { //before
private int id;
private int amount;
public Item(@JsonProperty("id") int id, @JsonProperty("amount") int amount) {
this.id = id;
this.amount = amount;
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor //I don't want this here as it could cause complications in other places. But json requires I have this...
public class Item { //after
private int id;
private int amount;
}
I don't want to use the NoArgsConstructor annotation by lombok as I don't want a no args constructor for this class. I realise that I could do this:
private Item() {
}
But was hoping there is a better way...
Since lombok 1.18.4, you can configure what annotations are copied to the constructor parameters. Insert this into your lombok.config
:
lombok.copyableAnnotations += com.fasterxml.jackson.annotation.JsonProperty
Then just add @JsonProperty
to your fields:
@Data
@AllArgsConstructor
public class Item {
@JsonProperty("id")
private int id;
@JsonProperty("amount")
private int amount;
}
Although the annotation parameters may seem unnecessary, they are in fact required, because at runtime the names of the constructor parameters are not available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With