Home > database >  Spring Boot parse JSON data to Java Class with different field names
Spring Boot parse JSON data to Java Class with different field names

Time:01-17

I am new to Spring Boot and I am trying to figure out how to parse json data. I see a lot of tutorials on how to map json string object to an annotated Java class and using and object mapper, like this:

json:

{
    "UUID": "xyz",
    "name": "some name"
}

public class MyClass{ 
    @JsonProperty 
    private UUID id;
    @JsonProperty
    private String name;

    @JsonAnyGetter
    public UUID getId() {
        return this.id;
    }
    @JsonAnySetter
    public void setId(UUID id) {
        this.id = id;
    }
    @JsonAnyGetter
    public String getName() {
        return this.name;
    }
    @JsonAnySetter
    public void setName(String name) {
        this.name = name;
    }
}   

ObjectMapper objectMapper = new ObjectMapper();
MyClass customer = objectMapper.readValue(jsonString, MyClass.class);

The problem is that the system I am getting the json string from does not match the class naming conventions we use (and I cannot change either one). So, instead of having the example json string above, it might look like this:

 {
    "randomdstring-fieldId": "xyz",
    "anotherrandomstring-name": "some name"
}  

This use case only has two fields, but my use case has a larger payload. Is there a way to either map the field names from the json object to the field names in the Java class or is there a way to just parse the json string as a key value pair (so that I can just manually add the fields to my Java object)?

CodePudding user response:

In Jackson with @JsonProperty you can customize the field name with it's annotation parameter value

Therefore, you just have to annotate the entity fields with the @JsonProperty annotation and provide a custom JSON property name, like this:

public class MyClass{ 
    @JsonProperty("original_field_name_in_json") 
    private UUID id;
...

CodePudding user response:

The @JsonProperty will do it for you:

@JsonProperty("name_in_json") 
private Long value;
  • Related