가장 대중적인 MIME 타입인 JSON 형식을 java에서 객체로 변환하기 위해 어떻게 해야하는지 알아보자.
{
"name": "John Doe",
"age": 30,
"email": "johndoe@example.com",
"isVerified": true
}
json 데이터이다. 이런 데이터가 나에게 왔다고 할 때를 생각해보며 파싱해보자
자바에서 사용할 수 있게 문자열로 바꿔주자.
String jsonString = "{"
+ "\"name\":\"John Doe\","
+ "\"age\":30,"
+ "\"email\":\"johndoe@example.com\","
+ "\"isVerified\":true"
+ "}";
라이브러리도 추가해주자.
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
implementation 'com.fasterxml.jackson.core:jackson-databind:2.14.2'
매핑될 Java 클래스도 정의 해주자
public class User {
private String name;
private int age;
private String email;
private boolean isVerified;
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isVerified() {
return isVerified;
}
public void setVerified(boolean verified) {
isVerified = verified;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", email='" + email + '\'' +
", isVerified=" + isVerified +
'}';
}
}
준비는 끝났다.
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) {
String jsonString = "{"
+ "\"name\":\"John Doe\","
+ "\"age\":30,"
+ "\"email\":\"johndoe@example.com\","
+ "\"isVerified\":true"
+ "}";
try {
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(jsonString, User.class);
System.out.println(user);
//User{name='John Doe', age=30, email='johndoe@example.com', verified=true}
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}
결과가 이쁘게 나오는 것을 알 수 있다. 매핑만 잘하면 잘되겠다는 생각이 든다.
Share article