헤르메스 LIFE

[Jackson] ObjectMapper, String to Map, to List, Object to JSON 본문

Core Java

[Jackson] ObjectMapper, String to Map, to List, Object to JSON

헤르메스의날개 2021. 1. 31. 20:09
728x90

https://hermeslog.tistory.com/710

 

[ModelMapper] Object to Object 변환

Object 변환에는 여러 가지 툴이 있습니다. ObjectMapper 나 BeanUtil 등입니다. https://hermeslog.tistory.com/483 [Jackson] ObjectMapper, String to Map, to List, Object to JSON Object를 Map으로 변경 Json 데이터를 Map으로 변경 Js

hermeslog.tistory.com


Object를 Map으로 변경

Json 데이터를 Map으로 변경

Json 데이터를 List로 변경

Object를 Json으로 변경

package test.json;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class JacksonSample {
    
    private static Logger logger = LoggerFactory.getLogger( JacksonSample.class );
    
    public static void main( String ... args ) {
        
        Map<String, Object> rMap = convJsonToMap( getSampleMap() );
        logger.debug( "result :: {}", rMap );
        
        List<Object> rList = convJsonToList( getSampleList() );
        logger.debug( "result :: {}", rList );
        
        String json = convObjectToJson( getObjectList() );
        logger.debug( "result :: {}", json );
        
        toBeauty( getObjectList() );
    }
    
    /**
     * Json String -> Map
     * 
     * @param dto
     * @return
     */
    public static Map<String, Object> convJsonToMap( String json ) {
        ObjectMapper        objectMapper = new ObjectMapper();
        
        Map<String, Object> map          = null;
        try {
            map = objectMapper.readValue( json, new TypeReference<Map<String, Object>>() {} );
        } catch ( IOException e ) {
            throw new RuntimeException( e );
        }
        
        return map;
    }
    
    /**
     * Json String -> List
     * 
     * @param dto
     * @return
     */
    public static List<Object> convJsonToList( String json ) {
        ObjectMapper objectMapper = new ObjectMapper();
        
        List<Object> list         = null;
        try {
            list = objectMapper.readValue( json, new TypeReference<List<Object>>() {} );
        } catch ( IOException e ) {
            throw new RuntimeException( e );
        }
        
        return list;
    }

    /**
     * Object -> Json String
     * 
     * @param dto
     * @return
     */
    public static String convObjectToJson( Object dto ) {
        ObjectMapper objectMapper = new ObjectMapper();
        
        String       body         = null;
        try {
            body = objectMapper.writeValueAsString( dto );
        } catch ( IOException e ) {
            throw new RuntimeException( e );
        }
        
        return body;
    }
    
    /**
     * Object -> Json String 예쁘게 찍기
     * 
     * @param dto
     * @return
     */
    public static void toBeauty( Object json ) {
        ObjectMapper objectMapper = new ObjectMapper();
        
        String       jStr         = null;
        try {
            jStr = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString( json );
        } catch ( JsonProcessingException e ) {
            throw new RuntimeException( e );
        }
        
        logger.debug( "{}", jStr );
    }
    
    
    public static String getSampleMap() {
        StringBuffer jMap = new StringBuffer();
        jMap.append( "{ \"ID\": \"4\", \"USERNAME\":\"aa\", \"PASSWORD\": \"aa\", \"ROLE_ID\": \"1\", \"STATUS\": \"D\" }" );
        
        return jMap.toString();
    }
    
    public static String getSampleList() {
        StringBuffer jList = new StringBuffer();
        jList.append( "[" );
        jList.append( "{ \"ID\": \"4\", \"USERNAME\":\"aa\", \"PASSWORD\": \"aa\", \"ROLE_ID\": \"1\", \"STATUS\": \"D\" }," );
        jList.append( "{ \"ID\": \"5\", \"USERNAME\":\"bb\", \"PASSWORD\": \"bb\", \"ROLE_ID\": \"2\", \"STATUS\": \"D\" }," );
        jList.append( "{ \"ID\": \"6\", \"USERNAME\":\"cc\", \"PASSWORD\": \"cc\", \"ROLE_ID\": \"3\", \"STATUS\": \"D\" }" );
        jList.append( "]" );
        
        return jList.toString();
    }
    
    public static List<Object> getObjectList() {
        List<Object> list = new ArrayList<>();
        list.add( new User( "4", "한글", "aa", "1", "D" ) );
        list.add( new User( "5", "bb", "bb", "2", "D" ) );
        list.add( new User( "6", "cc", "cc", "3", "D" ) );
        
        return list;
    }
}

class User implements Serializable {
    
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    public User( String id, String password ) {
        this.id       = id;
        this.password = password;
    }
    
    public User( String id, String username, String password, String roleId, String status ) {
        this.id       = id;
        this.password = password;
        this.username = username;
        this.roleId   = roleId;
        this.status   = status;
    }
    
    private String id;
    private String password;
    private String username;
    private String roleId;
    private String status;

    
    public String getId() {
        return id;
    }

    
    public void setId( String id ) {
        this.id = id;
    }

    
    public String getPassword() {
        return password;
    }

    
    public void setPassword( String password ) {
        this.password = password;
    }

    
    public String getUsername() {
        return username;
    }

    
    public void setUsername( String username ) {
        this.username = username;
    }

    
    public String getRoleId() {
        return roleId;
    }

    
    public void setRoleId( String roleId ) {
        this.roleId = roleId;
    }

    
    public String getStatus() {
        return status;
    }

    
    public void setStatus( String status ) {
        this.status = status;
    }
    
}

DEBUG: test.json.JacksonSample - result :: {ID=4, USERNAME=aa, PASSWORD=aa, ROLE_ID=1, STATUS=D}
DEBUG: test.json.JacksonSample - result :: [{ID=4, USERNAME=aa, PASSWORD=aa, ROLE_ID=1, STATUS=D}, {ID=5, USERNAME=bb, PASSWORD=bb, ROLE_ID=2, STATUS=D}, {ID=6, USERNAME=cc, PASSWORD=cc, ROLE_ID=3, STATUS=D}]
DEBUG: test.json.JacksonSample - result :: [{"id":"4","password":"aa","username":"한글","roleId":"1","status":"D"},{"id":"5","password":"bb","username":"bb","roleId":"2","status":"D"},{"id":"6","password":"cc","username":"cc","roleId":"3","status":"D"}]
DEBUG: test.json.JacksonSample - [ {
"id" : "4",
"password" : "aa",
"username" : "한글",
"roleId" : "1",
"status" : "D"
}, {
"id" : "5",
"password" : "bb",
"username" : "bb",
"roleId" : "2",
"status" : "D"
}, {
"id" : "6",
"password" : "cc",
"username" : "cc",
"roleId" : "3",
"status" : "D"
} ]

package test.mapper;

import java.io.Serializable;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

public class ObjectMapperSample {
    
    public static void main(String... args) {
        ObjectMapper   objectMapper = new ObjectMapper();
        BoardSearchDto dto          = BoardSearchDto.builder()
                .keyword("keyword")
                .searchType("searchType")
                .page(1)
                .recordSize(10)
                .pageSize(10)
                .build();
        
        Map<String, Object> map = objectMapper.convertValue(dto, Map.class);
        
        System.out.println("map :: " + map);
        
        BoardSearchDto board = objectMapper.convertValue(map, BoardSearchDto.class);
        
        // [실행 결과]
        System.out.println("board :: " + board);
    }
}

@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString
class BoardSearchDto {
    private static final long serialVersionUID = 1L;
    
    private int    page;       // 현재 페이지 번호
    private int    recordSize; // 페이지당 출력할 데이터 개수
    private int    pageSize;   // 화면 하단에 출력할 페이지 사이즈
    private String keyword;    // 검색 키워드
    private String searchType; // 검색 유형
}

map :: {page=1, recordSize=10, pageSize=10, keyword=keyword, searchType=searchType}
board :: BoardSearchDto(page=1, recordSize=10, pageSize=10, keyword=keyword, searchType=searchType)

https://hermeslog.tistory.com/710

 

[ModelMapper] Object to Object 변환

Object 변환에는 여러 가지 툴이 있습니다. ObjectMapper 나 BeanUtil 등입니다. https://hermeslog.tistory.com/483 [Jackson] ObjectMapper, String to Map, to List, Object to JSON Object를 Map으로 변경 Json 데이터를 Map으로 변경 Js

hermeslog.tistory.com

 

728x90