java로 프로그램을 할 때 파라미터로 가장 많이 사용하게 되는 ObjectVO 객체이고 VO로 값을 받거나 전달해야 하는 경우 VO의 값을 확인 하려면 디버깅모드에서 Variables에 있는 값을 확인 하거나 Vo.getXxx()로 하나씩 출력을 해봐야 하는 불편함이 있는데 ObjectMapper를 이용하면 VoJSON 형태로 변환하여 사용할 수 있습니다.



 

먼제 pom.xml에 라이브러리를 등록 합니다.

 

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->

        <dependency>

            <groupId>com.fasterxml.jackson.core</groupId>

            <artifactId>jackson-databind</artifactId>

            <version>2.11.0</version>

        </dependency>

 

main 으로 사용할 VO 파일을 생성 합니다.

 

public class SampleVo {

 

        private String username; /* 사용자ID*/

        private String name; /* 이름*/

        private Map<String, Object> mobile; /* 휴대전화*/

        private Map<String, Object> tel; /* 전화번호*/

       

        //getXxx, setXxx 생략

       

}

 

VO를 또 생성 합니다이건 Map<String, Object>로 설정한 mobile을 위한 Vo 입니다.


public class MovileVo {

 

        private String mobile1; /* 휴대전화1*/

        private String mobile2; /* 휴대전화2*/

        private String mobile3; /* 휴대전화3*/

       

        //getXxx, setXxx 생략

       

}

 

 

tel을 위한 Vo도 하나 더 추가 합니다.


public class TelVo {

 

        private String tel1; /* 전화번호1*/

        private String tel2; /* 전화번호2*/

        private String tel3; /* 전화번호3*/

       

        //getXxx, setXxx 생략

}

 

 

이제 Controller를 하나 만들고 코딩을 합니다.

MovileVo TelVo에 값을 설정하고 SampleVoMobileVoTelVo를 이용하여 값을 설정 합니다.



import com.fasterxml.jackson.databind.ObjectMapper;


        @RequestMapping(value = "/sample/test")

        public void sampleMethod(Model model) throws Exception {

              

               SampleVo sampleVo = new SampleVo();

               MovileVo movileVo = new MovileVo();

               TelVo telVo = new TelVo();

              

               movileVo.setMobile1("010");

               movileVo.setMobile2("1111");

               movileVo.setMobile3("2222");

              

               telVo.setTel1("02");

               telVo.setTel2("111");

               telVo.setTel3("2222");

              

               Map<String, Object> movileMap = new HashMap<String, Object>();

               Map<String, Object> telMap = new HashMap<String, Object>();

              

               movileMap.put("movile1", movileVo.getMobile1());

               movileMap.put("movile2", movileVo.getMobile2());

               movileMap.put("movile3", movileVo.getMobile3());

              

               telMap.put("tel1", telVo.getTel1());

               telMap.put("tel2", telVo.getTel2());

               telMap.put("tel3", telVo.getTel3());

              

               sampleVo.setUsername("copycoding");

               sampleVo.setName("카피코딩");

               sampleVo.setMobile(movileMap);

               sampleVo.setTel(telMap);

              

               ObjectMapper mapper = new ObjectMapper();

               String samString = mapper.writeValueAsString(sampleVo);

              

               System.out.println("=== sampleVo ===" + samString);

        }

 

ObjectMapper mapper = new ObjectMapper();

String samString = mapper.writeValueAsString(sampleVo);

ObjectMapper를 설정 하고 writeValueAsString()을 이용하면 JSON 형태의 String 값을 얻을 수 있습니다.

 

localhost:8080/sample/test를 호출하여 실행을 하여 log를 확인 해 봅니다.

 

=== sampleVo ==={"username":"copycoding","name":"카피코딩","tel":{"tel1":"02","tel2":"111","tel3":"2222"},"mobile":{"movile1":"010","movile3":"2222","movile2":"1111"}}

 

String형이라 다시 정리 하면

=== sampleVo ===

{

"username":"copycoding",

  "name":"카피코딩",

  "tel":{

        "tel1":"02",

        "tel2":"111",

        "tel3":"2222"

      },

  "mobile":{

        "movile1":"010",

        "movile3":"2222",

        "movile2":"1111"

      }

}

 

이런 결과를 볼 수 있습니다.


- copy coding -


1. substring

 

문자열중 일부를 뽑아오거나 여러 Data를 하나의 문자열로 받아 다시 각 항목별로 나누어 분류하는데 많이 사용합니다중간에 구분자가 없는 경우에 사용합니다.  문자열이 길어지면 눈이 튀어나와 힘들죠.


substring의 정의는 다음과 같습니다.

public String substring(int beginIndex, int endIndex)

  beginIndex : 시작 index

  endIndex : 종료 index

 

사용시 주의 사항은 beginIndex0에서 시작하고 endIndex는 자르려는 글자 끝 index보다 1을 더해줘야 합니다.

 String str = “ABCDEFGHIJKL”;

문자열

A

B

C

D

E

F

G

H

I

J

K

L

Index

0

1

2

3

4

5

6

7

8

9

10

11

 

A부터 C까지만 잘라 오려면

String getStr1 = str.substring(0, 3);


D부터 K까지만 잘라 오려면

String getStr2 = str.substring(3, 11);

 

F부터 끝까지 가져오려면

String getStr3 = str.substring(5);


간단한 테스트 입니다.

        public static void subString() {

              

               String str = "ABCDEFGHIJKL";

              

               String getStr1 = str.substring(0, 3);

               String getStr2 = str.substring(3, 11);

               String getStr3 = str.substring(5);

              

               System.out.println("str.substring(0, 3) : "+ getStr1);

               System.out.println("str.substring(3, 11) : "+ getStr2);

               System.out.println("str.substring(5) : "+ getStr3);

              

        }


java substring split



2. split

 

substring과 같이 여러 Data를 구분자를 추가하여 하나의 문자열로 묶어서 수신한 후 다시 나누거나 문자열에 규칙적인 반복 문자가 있을 경우 이용하여 문자열을 나누어 배열화 하는 기능입니다중간에 꼭 규칙적인 문자가 있어야 가능하겠죠.

 

split의 정의는 다음과 같습니다.

public String[] split(String regex)

regex : 규칙적 어구

  

기호를 구분자로

 

String str1 = "A-B-CDEFG-HIJKL";

str1 문자열에는 “-“ 이 문자가 반복되어 구분자로 사용할 수 있습니다.

String getStr1[] = str1.split("-");

이렇게 하면 getStr1[] 배열에 문자열이 “-“으로 나뉘어져 들어가게 됩니다. 주민번호, 전화번호등에 가장 많이 사용하는 방법이죠.

 

String str1 = "A-B-CDEFG-HIJKL";

 

String getStr1[] = str1.split("-");

 

for(int i=0; i<getStr1.length;i++) {

        System.out.println("getStr1 ["+ i + "] : " + getStr1[i]);

}


java substring split



문자를 구분자로

 

String str2 = "ABTTCDETTFGHIJKTTL";

str2 문자열에는 “TT” 문자가 반복적으로 들어있어 구분자로 사용할 수 있습니다.

 

String getStr2[] = str2.split("TT");

이렇게 하면 “TT”로 구분된 문자가 getStr2[] 배열에 들어갑니다

 

String str2 = "ABTTCDETTFGHIJKTTL";

 

String getStr2[] = str2.split("TT");

 

for(int i=0; i<getStr2.length;i++) {

        System.out.println("getStr2 ["+ i + "] : " + getStr2[i]);

}


java substring split



특수문자를 구분자로

 

String str2 = "A|B|CDEFG|HIJKL";

str2는 특수문자 “|”가 중간에 구분자로 들어가 있습니다. 특수문자를 일반적인 문자처럼 구분자로 사용하게 되면 엉뚱한 결과가 나옵니다. 엉뚱하다기 보다는 그냥 글자를 하나씩 배열에 입력하고 끝나게 됩니다. 이런 경우는 두가지 방법으로 처리를 하는데 하나는 특수문자 앞에 “\\”를 써주거나 특수문자를 “[]”로 감싸줍니다.

 

        String str3 = "A|B|CDEFG|HIJKL";

              

//      String getStr3[] = str3.split("[|]");

// String getStr3[] = str3.split("[.]");

        String getStr3[] = str3.split("\\|");

       

        for(int i=0; i<getStr3.length;i++) {

               System.out.println("getStr3 ["+ i + "] : " + getStr3[i]);

        }


java substring split


- copy coding -


1

+ Recent posts