首页 > 解决方案 > Java 将一个 JSON 字段解析为两个 Java 字段而无需设置器

问题描述

我正在使用 sprintboot,我有一个模型,例如:

public class Source {

    # I have 10 annotation here validator
    # @NotNull @Deserializer and other
    public String raw_data;

    # I have 10 annotation here validator
    # @NotNull @Deserializer and other
    public String fix_data;  

    # i have more than 100+ other field
}

我想将这些数据解析成固定版本,但仍保留原始原始版本。

{"data":"somedata"}

数据不能以数字开头。

所以我希望我的java类被解析为:

public class Source {
    public String raw_data = "1abc";
    public String fix_data = "abc";
}

我尝试使用@JsonAlias但没有用。我也尝试使用@JsonProperty,但我得到了error: Multiple fields representing property.

如何将 json 值解码为两个字段?

标签: javajsonspring-boot

解决方案


您可以使用 @JsonCreator 应用于构造函数来反序列化提到的 JSON 结构。

public class Source {

    public String rawData;
    public String fixdata;

    @JsonCreator
    public Source(@JsonProperty("data") String data) {
        this.rawData = data;
        this.fixData = data.replaceAll("^(\\d+)", ""); // removing digits at the start
    }
}

测试

String json = "{\"data\":\"1abc\"}";
ObjectMapper mapper = new ObjectMapper();
Source src = mapper.readValue(json, Source.class);
System.out.printf("raw: '%s', input: '%s'%n", src.rawData, src.fixData);

输出:

raw: '1abc', input: 'abc'

推荐阅读