问题
Is there a way to specify different serialized/deserialized JSON field names without having to write out both getter and setter methods explicitly, perhaps using lombok getters and setters?
As similar to this example, the following code permits incoming JSON to be deserialized to a different POJO field name. It also causes the POJO field name to be serialized as is:
public class PrivacySettings {
private String chiefDataOfficerName;
@JsonProperty("CDO_Name__c")
private void setChiefDataOfficerName(String chiefDataOfficerName) {
this.chiefDataOfficerName = chiefDataOfficerName;
}
@JsonProperty("chiefDataOfficerName")
private String getChiefDataOfficerName() {
return chiefDataOfficerName;
}
}
This seems verbose, but I haven't been able to get this to work with @Getter and @Setter. I did see that Jackson supports @JsonAlias which would probably help in this particular example, but I also have need to serialize with a different name.
Seems like this should be very simple, something like:
@Getter
@Setter
public class PrivacySettings {
@JsonSetter("CDO_Name__c")
@JsonGetter("chiefDataOfficerName")
private String chiefDataOfficerName;
}
But of course this is not valid.
回答1:
I particularly don't see anything wrong with a getter and a setter for this situation.
However, if you want to try, since v0.11.8 Lombok supports an experimental feature to add annotations to generated getters and setters. See the documentation:
To put annotations on the generated method, you can use
onMethod=@__({@AnnotationsHere})
; to put annotations on the only parameter of a generated setter method, you can useonParam=@__({@AnnotationsHere})
. Be careful though! This is an experimental feature. For more details see the documentation on the onX feature.
The syntax for this feature depends on JDK version. For JDK 8, you'll have:
public class PrivacySettings {
@Setter(onMethod_ = { @JsonSetter("CDO_Name__c") })
@Getter(onMethod_ = { @JsonGetter("chiefDataOfficerName") })
private String chiefDataOfficerName;
}
For JDK 7, the syntax is:
public class PrivacySettings {
@Setter(onMethod = @__({ @JsonSetter("CDO_Name__c") }))
@Getter(onMethod = @__({ @JsonGetter("chiefDataOfficerName") }))
private String chiefDataOfficerName;
}
For further details, check the @Getter and @Setter documentation. Also see this answer for details on @__()
.
来源:https://stackoverflow.com/questions/49886553/custom-serialized-and-deserialized-field-names-with-lombok