英文:
Jackson: Deserialize one value to two java fields
问题
// JSON 中有一个字段
{
"Number": "2737212281"
}
// 我想将这个字段反序列化为两个 Java 字段
@Column(name = "TRANSACTION_CURRENCY", length = 5)
@JsonProperty("TransactionCurrency")
@JsonAlias({"Number"})
private String TransactionCurrency;
@Column(name = "SD_DOCUMENT_REASON", length = 3, nullable = true)
@JsonProperty("SDDocumentReason")
@JsonProperty("Number")
private String SDDocumentReason;
// 为了某种原因,该库只会取第一个字段的值(TransactionCurrency)
英文:
So I have one field in my JSON
{
"Number": "2737212281"}
And I want to deserialize this field to two java fields
@Column(name = "TRANSACTION_CURRENCY", length = 5)
@JsonProperty("TransactionCurrency")
@JsonAlias({"Number"})
private String TransactionCurrency;
@Column(name = "SD_DOCUMENT_REASON", length = 3, nullable = true)
@JsonProperty("SDDocumentReason")
@JsonProperty("Number")
private String SDDocumentReason;
to have the same value in both fields, for some reason the lib just takes the first field(TransactionCurrency)
答案1
得分: 1
使用@JsonCreator
可能是一个选项。
例如,对于类似以下 JSON 结构:{ "field" : "anything" }
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
class Foo {
private final String field0;
private final String field1;
@JsonCreator
public Foo(@JsonProperty("field") String value) {
this.field0 = value;
this.field1 = value;
}
}
英文:
Using @JsonCreator
could be an option.
For example, for JSON that looks like: { "field" : "anything" }
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
class Foo {
private final String field0;
private final String field1;
@JsonCreator
public Foo(@JsonProperty("field") String value) {
this.field0 = value;
this.field1 = value;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论