Usage of Jackson @JsonProperty annotation for kotlin data classes
@JsonProperty
annotations in your code are all put on private fields within your data class and by default Jackson doesn't scan private fields for annotations. You have to instruct it to do otherwise by putting @JsonAutoDetect
annotation:
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
data class CurrencyInfo(
@JsonProperty("currency_info") var currencyInfo: CurrencyInfoItem?
)
or alternatively you can move your annotations on accessor methods:
data class CurrencyInfo(
@get:JsonProperty("currency_info") var currencyInfo: CurrencyInfoItem?
)
You can do something like this:
data class CurrencyInfo @JsonCreator constructor (
@param:JsonProperty("currency_info")
@get:JsonProperty("currency_info")
val currencyInfo: CurrencyInfoItem?
)
code above translates to java as:
public final class CurrencyInfo {
@Nullable
private final String currencyInfo;
@JsonProperty("currency_info")
@Nullable
public final String getCurrencyInfo() {
return this.currencyInfo;
}
@JsonCreator
public CurrencyInfo(@JsonProperty("currency_info") @Nullable String currencyInfo) {
this.currencyInfo = currencyInfo;
}
}
code from accepted answer translates to java as following:
First (is not pure immutable):
@JsonAutoDetect(
fieldVisibility = Visibility.ANY
)
public final class CurrencyInfo {
@Nullable
private String currencyInfo;
@Nullable
public final String getCurrencyInfo() {
return this.currencyInfo;
}
public final void setCurrencyInfo(@Nullable String var1) {
this.currencyInfo = var1;
}
public CurrencyInfo(@JsonProperty("currency_info") @Nullable String currencyInfo) {
this.currencyInfo = currencyInfo;
}
}
Second (probably has problems with deserialization):
public final class CurrencyInfo {
@Nullable
private final String currencyInfo;
@JsonProperty("currency_info")
@Nullable
public final String getCurrencyInfo() {
return this.currencyInfo;
}
public CurrencyInfo(@Nullable String currencyInfo) {
this.currencyInfo = currencyInfo;
}
}
You can add the jackson-module-kotlin
(https://github.com/FasterXML/jackson-module-kotlin) and register the kotlin module with jackson:
val mapper = ObjectMapper().registerModule(KotlinModule())
Then it (and many other things) works automagically.
You can configure the ObjectMapper from the jackson library by calling the method setPropertyNamingStrategy(...)
Using PropertyNamingStrategy.SNAKE_CASE
should resolve your problem
See also the other available strategies here : PropertyNamingStrategy