See below for easy usage Jackson usage memo
In this article, I would like to summarize usage examples.
public class SampleDTO {
private String field1;
private List<String> field2;
private SomeClass field3;
public String getField1(){return field1};
public List<String> getField2(){return field2};
public SomeClass getField3(){return field3};
public String getField3Text(){return field3.getText()};
}
SampleDTO dto = new SampleDTO();
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(dto);
SampleDTO dto = new SampleDTO();
ObjectMapper mapper = new ObjectMapper();
ObjectNode jsonNode = mapper.valueToTree(dto);
SampleDTO dto = new SampleDTO();
ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.readerForUpdating(dto);
reader.readValue(json);
Annotate the items you want to ignore as shown below.
@JsonIgnore
private String field1;
Annotate the items you want to change as follows.
@JsonProperty("fieldA")
private String field1;
In such a case, it would be {"fieldA": "\ <field1 value >"}.
@JsonProperty can also be applied to methods.
@JsonProperty("fieldA")
public String getField1(){
...
}
//If there is a method that conflicts with the value set in JsonProperty
//Give Json Ignore to those who do not need it.
@JsonIgnore
public String getFieldA(){
...
}
//In this case, mutual conversion cannot be done well unless the setter is also defined.
@JsonSetter("fieldA")
public void setField1(String field1){
...
}
If the following fields are defined, If you output as it is, the field name output to JSON will be camel case.
private String sampleField;
You can also change the field name using @JsonProperty, Use Property Naming Strategy if you want to convert all fields according to a specific rule. For camel case ⇒ snake case, there is a default conversion logic, so you can use it.
ObjectMapper mapper = new ObjectMapper();
//Renaming rule settings
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
If you want to format the output JSON string, change the mapper settings. For example, to set an appropriate indent, do as follows.
//JSON to output
mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);