[Java] Json String to Object, Json String to List<Object> :: @JsonProperty

동민·2022년 2월 22일
0

import

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

전역변수 선언

// thread safe
private static final ObjectMapper mapper = new ObjectMapper();
  1. Json String to Object
/*
{
    "r1" : "결과1",
    "r2" : "결과2"
}
*/
String result = "{ " +
                "\"r1\" : \"결과1\", " +
                "\"r2\" : \"결과2\" " +
                " }";
                
ResultDTO data = null;
if ( StringUtils.isNoneBlank(result) ) {
    try {
        data = mapper.readValue(result, ResultDTO.class);
    } catch (JsonProcessingException e) {}
}
import com.fasterxml.jackson.annotation.JsonProperty;

@Data
public class ResultDTO {

    @JsonProperty("r1")
    private String result1;

    @JsonProperty("r2")
    private String result2;
}

아래와 같이 매핑 됨

result1: "결과1"
result2: "결과2"
  1. Json String to List<Object>
// [{"q": "1", "a": "1,2,3"}, {"q": "2", "a": "4"}, {"q": "3", "a": "홍길동"}]
String answer = "[{\"q\" : \"1\", \"a\" : \"1,2,3\"}, {\"q\" : \"2\", \"a\" : \"4\"}, {\"q\" : \"3\", \"a\" : \"홍길동\"}]";
        
List<AnswerData> list = null;
if ( StringUtils.isNoneBlank(answer) ) {
    try {
        list = mapper.readValue(answer, new TypeReference<List<AnswerData>>() {});
    } catch (JsonProcessingException e) {}
}
import com.fasterxml.jackson.annotation.JsonProperty;

@Data
public class AnswerData {

    @JsonProperty("q")
    private String question;

    @JsonProperty("a")
    private String answer;
}

아래와 같이 매핑됨

list[0]
question: "1"
answer: "1,2,3"

list[1]
question: "2"
answer: "4"

list[2]
question: "3"
answer: "홍길동"
  1. List<Object> to Json String 역방향
List<AnswerData> list = XXX;

String str = "";
if ( !CollectionUtils.isEmpty(list) ) {
    try {
        str = mapper.writeValueAsString(list);
    } catch (JsonProcessingException e) {}
}

return str;
profile
BE Developer

0개의 댓글