com.fasterxml.jacksonでjsonファイルを読み込むサンプル

2018年7月29日

1.example.json
{
“users":
[
{
“name": “yamada",
“addr": “oosaka",
“age": 22
},
{
“name": “oosaki",
“addr": “fukuoka",
“age": 32
},
{
“name": “oosaki",
“addr": “fukuoka",
“age": 32
}
]
}

2.JsonReadSample.java
package study;

import java.io.File;
import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonReadSample {

public static void main(String[] args) {
JsonReadSample converter = new JsonReadSample();
try {
converter.parse(“example.json");
} catch (JsonParseException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
}

public void parse(String fileName) throws JsonParseException, JsonMappingException, IOException {
UserInfoList userList = new ObjectMapper().readValue(new File(fileName), UserInfoList.class);
for (User user : userList.getUsers()) {
System.out.println(user.getName() + “–" + user.getCountry() + “–" + user.getAge());
}
}

public static class UserInfoList {
private List users;

public UserInfoList() {
}

public List getUsers() {
return users;
}

public void setUsers(List users) {
this.users = users;
}
}

public static class User {
private String name;
private String addr;
private int age;

public User() {
}

public String getName() {
return name;
}

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

public String getCountry() {
return addr;
}

public void setCountry(String addr) {
this.addr = addr;
}

public int getAge() {
return age;
}

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

Java

Posted by arkgame