Spring Boot: Object Mapper

๊น€์•„๋ฌด๊ฐœยท2023๋…„ 5์›” 3์ผ
0

Spring Boot ๐Ÿƒ

๋ชฉ๋ก ๋ณด๊ธฐ
8/95
post-custom-banner

ObjectMapper์˜ ๊ธฐ๋Šฅ

  1. Text ํ˜•ํƒœ์˜ JSON String์„ Object ํ˜•ํƒœ๋กœ ๋ฐ”๊ฟ”์ค€๋‹ค.
    ์ด๋•Œ, Object์—๋Š” Default ์ƒ์„ฑ์ž๊ฐ€ ์ •์˜๋˜์–ด ์žˆ์–ด์•ผ ํ•œ๋‹ค.

  2. Object๋ฅผ Text ํ˜•ํƒœ์˜ JSON String์œผ๋กœ ๋ฐ”๊ฟ”์ค€๋‹ค.
    ์ด๋•Œ, Object์—๋Š” ๊ธฐ๋ณธํ˜• getter() ๋ฉ”์†Œ๋“œ๊ฐ€ ์ •์˜๋˜์–ด ์žˆ์–ด์•ผ ํ•œ๋‹ค.
    ๋งŒ์•ฝ, ์‚ฌ์šฉ์ž ์ •์˜ ๋ฉ”์„œ๋“œ ์ค‘์— ์ด๋ฆ„์ด get์œผ๋กœ ์‹œ์ž‘ํ•˜๋Š” ๊ฒƒ์ด ์žˆ๋‹ค๋ฉด ์˜ค๋ฅ˜ ๋ฐœ์ƒ!


Controller์—์„œ ์‚ฌ์šฉ์‹œ Spring์ด ์•Œ์•„์„œ ํ•ด์ฃผ๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋งŽ์ง€๋งŒ,
์ด๋ฅผ ์ด์šฉํ•˜์ง€ ์•Š๊ณ  ์ง์ ‘ ObjectMapper๋ฅผ ํด๋ž˜์Šค๋กœ ํ˜ธ์ถœํ•ด์„œ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ๋‹ค.

์ด ๋ฐฉ๋ฒ•์— ๋Œ€ํ•œ ๊ฐ„๋‹จํ•œ ์˜ˆ์ œ๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค.


Object๋ฅผ Text๋กœ

var om = new ObjectMapper();
try {
	var user = new User("zh", 360, "010-1234-4321");
	var text = om.writeValueAsString(user);

	System.out.println(text);
    // ์ถœ๋ ฅ ๊ฐ’ : {"name":"zh","age":360,"phone_number":"010-1234-4321"}
} catch (JsonProcessingException e) {
	throw new RuntimeException(e);
}

text๋ฅผ Object๋กœ

์ด๋•Œ text๋Š” json ํ˜•์‹์„ ๋งŒ์กฑํ•˜๋Š” String์ด์–ด์•ผ ํ•จ.

var om = new ObjectMapper();
try {
	var text = om.writeValueAsString(user);
	var ou = om.readValue(text, User.class); 
    
	System.out.println(ou);
    // ์ถœ๋ ฅ ๊ฐ’ : User{name='zh', age=360, phoneNumber='010-1234-4321'}
} catch (JsonProcessingException e) {
	throw new RuntimeException(e);
}
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€