๊ฐ์ฒด์ ํ๋ ๊ฐ์ด null์ผ ๊ฒฝ์ฐ, JSON ์๋ต์๋ null ํ๋๊ฐ ํฌํจ๋จ.
๋ถํ์ํ ๋ฐ์ดํฐ๊ฐ ํฌํจ๋์ด API ์๋ต ํฌ๊ธฐ๊ฐ ์ฆ๊ฐํจ.
Jackson์ @JsonInclude(JsonInclude.Include.NON_NULL)์ ์ฌ์ฉํ์ฌ null ํ๋๋ฅผ ์ ๊ฑฐํ ์ ์์.
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
class Person {
public String name;
@JsonInclude(JsonInclude.Include.NON_NULL) // null ๊ฐ ์ ์ธ
public String nickname;
public Person(String name, String nickname) {
this.name = name;
this.nickname = nickname;
}
}
public class JsonNullExample {
public static void main(String[] args) throws Exception {
Person person = new Person("ํ๊ธธ๋", null);
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(person);
System.out.println(jsonString); // {"name":"ํ๊ธธ๋"}
}
}
JSON ํค ์ด๋ฆ๊ณผ Java ๊ฐ์ฒด ํ๋๋ช ์ด ๋ค๋ฅด๋ฉด ์ญ์ง๋ ฌํ ์คํจ (MismatchedInputException ๋ฐ์)
@JsonProperty("json_key")์ ์ฌ์ฉํ์ฌ JSON ํ๋๋ช ์ Java ๊ฐ์ฒด์ ํ๋๋ช ๊ณผ ๋งคํ.
import com.fasterxml.jackson.annotation.JsonProperty;
class User {
@JsonProperty("user_name") // JSON ํ๋๋ช
์ Java ํ๋์ ๋งคํ
public String name;
public User() {} // ๊ธฐ๋ณธ ์์ฑ์ ํ์
}
public class JsonPropertyExample {
public static void main(String[] args) throws Exception {
String jsonString = "{\"user_name\":\"ํ๊ธธ๋\"}";
ObjectMapper objectMapper = new ObjectMapper();
User user = objectMapper.readValue(jsonString, User.class);
System.out.println(user.name); // ํ๊ธธ๋
}
}
JSON์ ๊ฐ์ฒด๋ก ๋ณํํ ๋, ๊ธฐ๋ณธ ์์ฑ์๊ฐ ์์ผ๋ฉด ์ญ์ง๋ ฌํ๊ฐ ์คํจํจ.
com.fasterxml.jackson.databind.exc.InvalidDefinitionException ๋ฐ์.
๊ธฐ๋ณธ ์์ฑ์๋ฅผ ๋ฐ๋์ ์ถ๊ฐ.
class Employee {
public String name;
public int age;
// ๊ธฐ๋ณธ ์์ฑ์ ์์ผ๋ฉด ์ญ์ง๋ ฌํ ์ค๋ฅ ๋ฐ์!
public Employee() {}
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
}
Date ๋๋ LocalDateTime์ JSON์ผ๋ก ๋ณํํ ๋, ์ฌ๋์ด ์ฝ๊ธฐ ์ด๋ ค์ด timestamp(์ซ์)๋ก ๋ณํ๋จ.
API์์ ๋ ์ง๋ฅผ yyyy-MM-dd ํ์์ผ๋ก ์๋ต๋ฐ๊ณ ์ถ์ ๋ ๋ถํธํจ.
@JsonFormat์ ์ฌ์ฉํ์ฌ ๋ ์ง ํฌ๋งท์ ์ง์ .
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDate;
class Order {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
public LocalDate orderDate;
public Order(LocalDate orderDate) {
this.orderDate = orderDate;
}
}
{"orderDate": "2025-03-10"}
Lombok์ @Data ์ด๋
ธํ
์ด์
์ equals()์ hashCode()๋ฅผ ์๋ ์์ฑํ์ฌ ์ง๋ ฌํ ์ ์์์น ๋ชปํ ๋์์ ์ ๋ฐํ ์ ์์.
JSON์ ํฌํจ๋์ง ์์์ผ ํ ํ๋๊ฐ ์ง๋ ฌํ๋ ์๋ ์์.
@Getter, @Setter๋ง ์ฌ์ฉํ๊ฑฐ๋ @JsonIgnoreProperties(ignoreUnknown = true) ์ถ๊ฐ.
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true) // JSON์ ์๋ ํ๋๋ ๋ฌด์
class Product {
private String name;
}
์ด์ | ํด๊ฒฐ ๋ฐฉ๋ฒ |
---|---|
null ๊ฐ ํฌํจ ๋ฌธ์ | @JsonInclude(JsonInclude.Include.NON_NULL) |
JSON ํ๋๋ช ๋ถ์ผ์น | @JsonProperty("json_key") |
๊ธฐ๋ณธ ์์ฑ์ ์์ | ๊ธฐ๋ณธ ์์ฑ์ ์ถ๊ฐ |
๋ ์ง ํฌ๋งท ๋ฌธ์ | @JsonFormat(pattern = "yyyy-MM-dd") |
Lombok & Jackson ์ถฉ๋ | @JsonIgnoreProperties(ignoreUnknown = true) |