๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ๋ฐœ/JAVA

[JAVA] VO๋ฅผ JSON ๋ฐ์ดํ„ฐ๋กœ ๋ณ€ํ™˜ (java class to json, vo to json)

by ynzu๐Ÿค 2021. 12. 9.
๋ฐ˜์‘ํ˜•

๋จผ์ € ์•„๋ž˜ ํฌ์ŠคํŒ…์„ ๋ณด๊ณ  ํ•„์š”ํ•œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์ถ”๊ฐ€ํ•˜์ž!

 

[JAVA] JSON ๋ฐ์ดํ„ฐ๋ฅผ VO๋กœ ํŒŒ์‹ฑ, ๋ณ€ํ™˜ํ•˜๋Š” ๋ฐฉ๋ฒ• (json to java class)

๋จผ์ € jackson-databind ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์ถ”๊ฐ€ํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค! spring boot์˜ ๊ฒฝ์šฐ 'spring-boot-starter-web'์— ํฌํ•จ๋˜์–ด ์žˆ์Œ maven com.fasterxml.jackson.core jackson-databind 2.13.0 gradle // https://mvnrepos..

ynzu-dev.tistory.com

 

  • vo ์˜ˆ์‹œ
public class TestVo {

    @JsonProperty("user-name")
    private String userName;

    @JsonProperty("user-id")
    private String userId;
}

 

  • VO to JSON String
ObjectMapper mapper = new ObjectMapper(); 
String jsonString = mapper.writeValueAsString(TestVo);

 

  • ๊ฒฐ๊ณผ
{"user-name":"name01", "user-id":"id01"}

 

์•ž ํฌ์ŠคํŒ…์—์„œ ObjectMapper์˜ readValue ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด์„œ JSON String์„ vo๋กœ ๋ณ€ํ™˜ํ•ด์คฌ๋‹ค๋ฉด writeValueAsString์„ ์‚ฌ์šฉํ•˜๋ฉด vo๋ฅผ JSON String์œผ๋กœ ์ž๋™ ๋ณ€ํ™˜ํ•  ์ˆ˜ ์žˆ๋‹ค! 

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€