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'
user.json
[
    {
        "name": "amy",
        "age": 10
    },
    {
        "name": "john",
        "age": 25
    },
    {
        "name": "lisa",
        "age": 49
    }
]
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;
	}
}
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
You can rename the property using annotations as follows: (By default, Java field names are used)
@JsonProperty("name")
private String firstName;
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