简体   繁体   中英

Java parsing one JSON field to two Java fields without setters

I am using sprintboot and I have a model like:

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
}

I want to parse this data into a fixed version, but still retain the original raw version.

{"data":"somedata"}

The data can't start with a number.

  • "abc" would be valid
  • "1abc" would be invalid

So I want my java class to get parsed as:

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

I tried to use @JsonAlias but it didn't work. I also tried to use @JsonProperty but I got error: Multiple fields representing property .

How can I decode the json value into two fields?

Map data -> raw_data and in your method:

setRawData(String rawData){
  this.rawData = rawData;
  this.fixedData = rawData.replace("1", ""); // Whatever you do to fix it
}

You could use @JsonCreator applied to the constructor to deserialize the mentioned JSON structure.

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

Test

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM