Jackson:将一个值反序列化为两个Java字段

huangapple go评论59阅读模式
英文:

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;
    }
}

huangapple
  • 本文由 发表于 2020年10月2日 21:30:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/64172428.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定