[JAVA] Basic usage notes for Jackson

Install Jackson

build.gradle is as follows.

build.gragle


// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.9.1'

Basic usage

JSON you want to convert to an object

user.json


[
    {
        "name": "amy",
        "age": 10
    },
    {
        "name": "john",
        "age": 25
    },
    {
        "name": "lisa",
        "age": 49
    }
]

Class that maps JSON

UserJson.class


public class UserJson {
	private String name;
	private String age;

	public void getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}
}

Do the mapping

List<UserJson> userList = new ArrayList<UserJson>();
ObjectMapper mapper = new ObjectMapper();
try {
	user = mapper.readValue("json string", new TypeReference<List<UserJson>>() {
	});
} catch (IOException e) {
	//error
}

When mapped as above, the target Json is ʻuserList(List of ʻUserJson" It becomes).

If you define a getter in ʻUserJson`, you can access the element with a getter.

Access example with getter


System.out.println(userList.get(1).getName());
//Output: amy

tips

Change the property to any value

You can rename the property using annotations as follows: (By default, Java field names are used)

@JsonProperty("name")
private String firstName;

Ignore fields that do not exist in the mapped class

When mapping from JSON, an error will occur if there is a field that exists in `JSON but does not exist in the class to be mapped. To avoid this, write the following annotations in the mapping target.

UserJson.class


@JsonIgnoreProperties(ignoreUnknown = true)
public class UserJson {

...

Recommended Posts

Basic usage notes for Jackson
Jackson Common Usage Notes
Notes for AST analysis
Maven basic study notes
[Java] Basic method notes
[Java] Basic statement for beginners
swift CollectionView Super basic usage
Super basic usage of Eclipse
Basic usage of java Optional Part 1
Notes for Android application development beginners
Sort in List, for personal notes
Spring Security usage memo Basic / mechanism
Thymeleaf usage notes in Spring Boot
Docker related commands (notes for yourself)