Jackson Common Usage Notes

First of all

See below for easy usage Jackson usage memo

In this article, I would like to summarize usage examples.

Sample DTO

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

Generate JSON text from DTO

SampleDTO dto = new SampleDTO();
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(dto);

Generate ObjectNode from DTO

SampleDTO dto = new SampleDTO();
ObjectMapper mapper = new ObjectMapper();
ObjectNode jsonNode = mapper.valueToTree(dto);

Update DTO based on ObjectNode value

SampleDTO dto = new SampleDTO();
ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.readerForUpdating(dto);
reader.readValue(json);

Ignore unnecessary items

Annotate the items you want to ignore as shown below.

@JsonIgnore
private String field1;

Change the JSON key name

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){
...
}

Output camel case fields to JSON in snake case.

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

Mold when outputting JSON

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

Recommended Posts

Jackson Common Usage Notes
Basic usage notes for Jackson
Thymeleaf usage notes in Spring Boot