@
JsonAnyGetter
is used to serialize the properties of the map as they were actual properties
of the map.
public
class Employee {
private Map<String, String>
additionalInformation = new HashMap<>();
@JsonAnyGetter
public Map<String, String>
getAdditionalInformation() {
return additionalInformation;
}
public void
setAdditionalInformation(Map<String, String> additionalInformation) {
this.additionalInformation =
additionalInformation;
}
}
Find
the below working application.
package com.sample.model; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "firstName", "lastName", "hobbies", "id" }) public class Employee { @JsonProperty("EMPLOYEE_DD") private int id; @JsonProperty("EMPLOYEE_FIRST_NAME") private String firstName; @JsonProperty("EMPLOYEE_LAST_NAME") private String lastName; private Map<String, String> additionalInformation = new HashMap<>(); public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @JsonAnyGetter public Map<String, String> getAdditionalInformation() { return additionalInformation; } public void setAdditionalInformation(Map<String, String> additionalInformation) { this.additionalInformation = additionalInformation; } }
App.java
package com.sample.app; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.sample.model.Employee; public class App { public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException { Employee emp = new Employee(); emp.setFirstName("Hari Krishna"); emp.setLastName("Majety"); emp.setId(1); emp.getAdditionalInformation().put("hobby1", "Cricket"); emp.getAdditionalInformation().put("hobby2", "Football"); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(System.out, emp); } }
Output
{"EMPLOYEE_FIRST_NAME":"Hari
Krishna","EMPLOYEE_LAST_NAME":"Majety","EMPLOYEE_DD":1,"hobby2":"Football","hobby1":"Cricket"}
No comments:
Post a Comment