유정잉

33일차 Java [ Gson, Json, jQuery ] 본문

네이버 클라우드 부트캠프/복습 정리

33일차 Java [ Gson, Json, jQuery ]

유정♡ 2024. 4. 5. 12:27

Maven Repository: Search/Browse/Explore (mvnrepository.com)

Maven Repository: com.google.code.gson » gson (mvnrepository.com)

 

Gson 사용하는 이유 !!!
나중에 프로젝트 할때 네이버지도, 구글지도등 api 데이터를 가져올 때 필요함 !!!
api데이터를 java로 가져오는 법 

 

[ eclipse와 Gson 연결하기 ]

    1) Google에 mvn 검색

    2) mvn 사이트에서 Gson 검색

    3) 클릭 후 최신버전 클릭 -> jar 파일 다운로드

    4) 이클립스 -> Build Path -> Configure Build Path -> Class Path 클릭 후 -> Gson 파일 추가

         -> Referenced Library에 gson-2.10.1.jar 파일 추가 된 것 확인

 

 

[ eclipse와 Gson 활용하기 ]

    1) default package외에 새로운 package 생성

    2) 새로운 package에 DTO class 생성

    3) 필드선언 , 생성자생성, Getter&Setter 생성, 

package kr.bit; //새로운 패키지

public class FoodDTO { // DTO : 데이터 전달 객체
	private String name;
	private int price;
	private String rest;
	
	public FoodDTO() {} //기본생성자 1개
	public FoodDTO(String name, int price, String rest) { //매개변수 3개
		this.name=name;
		this.price=price;
		this.rest=rest;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	public String getRest() {
		return rest;
	}
	public void setRest(String rest) {
		this.rest = rest;
	}
	@Override
	public String toString() {
		return "FoodDTO[name=" + name + ", price=" + price + ", rest=" + rest + "]";
	}
	
}
import java.util.ArrayList; //기본 패키지
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import kr.bit.FoodDTO; //FoodDTO객체를 생성하려면 필요함

public class Test {
	public static void main(String[] args) {
	
		// 자바 objet => json(string)
		FoodDTO dto=new FoodDTO("김밥",7000,"a"); //생성자에 값 넣기	
		Gson g=new Gson();
		String str=g.toJson(dto); //dto를 str에 대입
		System.out.println(str); //가져온 데이터 출력
		
		// json => 자바 object
		FoodDTO dto1=g.fromJson(str,  FoodDTO.class);
		System.out.println(dto1);
		System.out.println(dto1.getName()); //키 값에 해당하는 value 값 출력
		System.out.println(dto1.getPrice());
		System.out.println(dto1.getRest());
		
		// list 객체 => json 
		List<FoodDTO> li=new ArrayList<FoodDTO>();
		li.add(new FoodDTO("김밥", 7000, "a"));
		li.add(new FoodDTO("우동", 10000, "b"));
		li.add(new FoodDTO("쫄면", 8500, "c"));
		
		String str2=g.toJson(li);
		System.out.println(str2);
		
		// json => li 객체
		List<FoodDTO> li2=g.fromJson(str2,  new TypeToken<List<FoodDTO>>() {}.getType());
		for(FoodDTO fo : li2) {
			System.out.println(fo);
		}
		
		
		
		
	//api 네이버 지도 구글지도 위도 경도 등등 데이터들이 json으로 들어가있어서 자바로 가져오는 법 !!
	// json : [ {aaa:123}, {bb:3444} ];
	// gson : java 객체를 json으로 변환
	//		  json을 java객체로 변환
	
	}
}

출력 결과

 

 

 


[ eclipse와 Json 연결하기 ]

1) mvn 검색창에 json 검색 -> jar 파일 다운로드 ( 최신 것 중 Usages가 젤 높은 것)

2) src -> New -> Others -> General -> File -> Next => text File 생성 

 

 

[ eclipse와 Json 활용하기 ]

  1) File 활용 없이 그냥 하는 법 

import org.json.JSONArray; //org 파일로 가져오기 !!!
import org.json.JSONObject;

public class Test2 {

	public static void main(String[] args) {
		//json이 들어있는 배열 생성
		JSONArray stu=new JSONArray();
		
		//객체를 json객체로 바꿔주는(만들어주는) 작업
		JSONObject stu2=new JSONObject();
		
		stu2.put("name", "홍길동");
		stu2.put("tel", "010-1111-2222");
		stu2.put("address", "seoul");
		System.out.println(stu2); //일반적으로 main에서 json객체에 삽입하는 방법
		
		stu.put(stu2);
		System.out.println(stu); //배열에 넣는 방법 : 배열형태로 출력됨

	}

}

 

2) 같은 package에 File 생성하고 그 File을 불러오는 방식 

    src -> New -> Others -> General -> File -> Next => text File 생성 

// File 생성 같은 package에 생성해야 함 !!!
{"food":[
	{
		"address":"seoul",
		"phone":"010-1111-2222",
		"name" : "hong"
	},
	{
		"addredd":"busan",
		"phone":"010-6666-8777"
		"name":"kim"
	}
]}
import java.io.InputStream;

import org.json.JSONArray; //반드시 org로 import
import org.json.JSONObject;
import org.json.JSONTokener;

public class Test3 {
	public static void main(String[] args) {
		
		String str="infom";
		InputStream is=Test3.class.getResourceAsStream(str); ;//file읽어오겠다는뜻
		if(is==null) {
			throw new NullPointerException("cannot find file");
		}
		
		JSONTokener to=new JSONTokener(is);  //json파일 파싱
		JSONObject ob=new JSONObject(to);
		JSONArray arr=ob.getJSONArray("student");
		System.out.println(arr);
		
		for(int i=0;i<arr.length();i++) {
			JSONObject stu=(JSONObject)arr.get(i);
			System.out.println(stu.get("name")+ "\t");
			System.out.println(stu.get("address")+ "\t");
			System.out.println(stu.get("phone")+ "\t");
		}
	}
}

 

 


jQuery CDN

 

jQuery CDN

jQuery CDN – Latest Stable Versions jQuery Core Showing the latest stable release in each major branch. See all versions of jQuery Core. jQuery 3.x jQuery 2.x jQuery 1.x jQuery Migrate jQuery UI Showing the latest stable release for the current and legac

releases.jquery.com

[ jQuery ]

   1) Google에 제이쿼리 CDN 검색

   2) 제일 최신버전 -> minified 클릭 -> 링크 복사 

   3) <head>와</head> 사이에 복사한 링크 삽입

<head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" ></script>
</head>

 

 

[  jQuery 기본적인 구조 ]

   1) css함수 : 스타일 변경 메서드 (스타일만 변경 가능 다른건 변경 불가능)

       $('선택자').css('속성' , '값'); //속성값이 하나 일 땐 쉼표(,) 사용

       $('선택자').css({'속성':'값' , '속성':'값'}); //속성값이 여러개 일 땐 중괄호{} 와 콜론(:) 사용

   2) children() : 선택자를 기준으로 자식요소 선택하는 메서드 

        => $('선택자').children('선택자');

        find() : 선택자를 기준으로 자손요소 선택하는 메서드 

         => $('선택자').find('선택자');

   3) siblings() : 선택자 기준으로 형제요소 선택하는 메서드

        => $('선택자').siblings ('선택자');

        parent() : 선택자 기준으로 부모요소 선택하는 메서드

        => $('선택자').parent ('선택자');

   4) next(), prev(), nextAll(), nextUntil(), prevUnil() : next랑 prev 제일 많이 사용 됨

       next() : 선택자 다음으로 다음꺼 prev() : 이전꺼

   5) eq(index) , 요소:first-child, 요소:last-child, 요소:nth-child

   6) 요소:gt(index) , 요소:lt(index), 문서객체.not('선택자'), 문서객체.has('선택자')

        gt(<) : 선택된 인덱스부터 다음의 모든 요소 선택

        lt(>) : 선택된 인덱스부터 이전의 모든 요소 선택

        not() : 선택자 제외하고(=이외) 모든 요소 선택

        has() : 선택요소를 포함(has)한 요소만 선택

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" ></script> <!-- defer 의미 찾아보기 -->
    <script>
        $(document).ready(function() {
            //실행코드
        });

        $(function() {

        });
    </script>
</head>
<body>
    <script>
        //실행코드
    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
	<script src="https://code.jquery.com/jquery-3.7.1.min.js" ></script>
	<script>
		$(document).ready(function() {
			//실행코드
		});

		$(function() {

		});
	</script>
</head>
<body>
	<script>
		//실행코드
	</script>
</body>
</html>

 

 

[  jQuery 응용 해보기 - 1 CSS 함수 ]

<!DOCTYPE html>
<head>
</head>
<body>
  <h1>자바 스크립트</h1>
  <p class="f">
    (서울=연합뉴스) 차지연 기자 = 중앙선거관리위원회는 22대 총선
    사전투표 첫날인 5일 오후 1시 현재 투표율이 8.00%로 집계됐다고 밝혔다.
    이날 오전 6시부터 진행된 사전투표에서 전체 유권자 4천428만11명
    가운데 354만1천778명이 투표를 마쳤다.
  </p>
  <script>
    //속성, 값을 1개만 사용
    $('h1').css('color','red');   //제이쿼리에선 document.getElementsByTagName이 필요없음 !!

    //속성, 값을 여러개 사용
    $('.f').css({
      'border':'2px solid deeppink',  //따옴표('')로 해줘야함 !!!
      'padding':'30px',
      'font-size':'20px'
    });
  </script>
</body>

</html>

 

[  jQuery 응용 해보기 - 2 children(), find() 함수 ]

<head>
</head>
<body>
    <div class="di" style="width: 500px;">
    <p>
        (서울=연합뉴스) 차지연 기자 = 중앙선거관리위원회는 22대 총선
        <span>사전투표</span> 첫날인 5일 오후 1시 현재 투표율이 8.00%로 집계됐다고 밝혔다.
    </p>
    <p>
        이날 <span>오전 6시부터</span> 진행된 사전투표에서 전체 유권자 4천428만11명
        가운데 354만1천778명이 투표를 마쳤다.
    </p>
    </div>
  <script>
        $('.di').css({'border':'2px solid aqua','padding':'20px'}); //따옴표('')로 해줘야함 !!!

        $('.di').children().css({ //.di를 기준으로 모든 자식요소룰 선택
            'color':'red','border':'2px solid red','padding':'20px'
        });
  </script>
</body>

<head>
</head>
<body>
    <div class="di" style="width: 500px;">
    <p>
        (서울=연합뉴스) 차지연 기자 = 중앙선거관리위원회는 22대 총선
        <span>사전투표</span> 첫날인 5일 오후 1시 현재 투표율이 8.00%로 집계됐다고 밝혔다.
    </p>
    <blockquote> <!-- 인용할 때 쓰는 태그 잘 쓰이지는 않음 참고하기 ~ -->
    <p>
        이날 <span>오전 6시부터</span> 진행된 사전투표에서 전체 유권자 4천428만11명
        가운데 354만1천778명이 투표를 마쳤다.</blockquote>
    </p>
    </div>
  <script>
        $('.di').css({'border':'2px solid aqua','padding':'20px'}); //따옴표('')로 해줘야함 !!!

        $('.di').children().css({ //.di를 기준으로 모든 자식요소룰 선택
            'color':'red','border':'2px solid red','padding':'20px'
        });

        //.di를 기준으로 blockquote로 자식요소를 선택 => 지정해서 값 줄 수도 있음
        $('.di').children('blockquote').css({ 'border':'2px solid yellow'});
  </script>
</body>

blockquote 활용해서 children('blockquote')에 지정해보기

<!DOCTYPE html>
<head>
</head>
<body>
    <div class="di" style="width: 500px;">
    <p>
        (서울=연합뉴스) 차지연 기자 = 중앙선거관리위원회는 22대 총선
        <span>사전투표</span> 첫날인 5일 오후 1시 현재 투표율이 8.00%로 집계됐다고 밝혔다.
    </p>
    <blockquote> <!-- 인용할 때 쓰는 태그 잘 쓰이지는 않음 참고하기 ~ -->
    <p>
        이날 <span>오전 6시부터</span> 진행된 사전투표에서 전체 유권자 4천428만11명
        가운데 354만1천778명이 투표를 마쳤다.</blockquote>
    </p>
    </div>
  <script>
        $('.di').css({'border':'2px solid aqua','padding':'20px'}); //따옴표('')로 해줘야함 !!!

        //.di를 기준으로 모든 자식요소룰 선택
        $('.di').children().css({
            'color':'red','border':'2px solid red','padding':'20px'
        });

        //.di를 기준으로 blockquote로 자식요소를 선택 => 지정해서 값 줄 수도 있음
        $('.di').children('blockquote').css({ 'border':'2px solid yellow'});

        //.di를 기준으로 자식의 자식 = <p>의<span>과 <blockquote>의<p>
        $('.di').children().children().css({ // .di > children * > children *
            'display':'block',
            'border':'2px solid green',
            'color':'yellowgreen'
        })

        //find는 그냥 태그만 찾는 것 ! = .di span
        $('.di').find('span').css('text-decoration','line-through');s
       
  </script>
</body>

</html>

 

 

[  jQuery 응용 해보기 - 3  siblings(), parent() 함수 ]

<head>
</head>
<body>
    <div class="di" style="width: 500px;">
        <a href="'#" class="a">li1</a>
        <a href="'#" class="a">li2</a>
        <a href="'#" class="a b">li3</a> <!-- class를 두개 쓸때는 공백 주기 -->
        <a href="'#" class="a">li4</a>
        <a href="'#" class="a">li5</a>
        <strong>안녕</strong>
    </div>
  <script>
        $('.a').css({
            'display':'block',
            'text-decoration':'none'
        });

        //형제요소 중에서 a태그만 선택하겠단 의미 / 그래서 <strong>태그인 안녕은 blue로 뜨지 않음
        $('.a').siblings('a').css({
            'color':'blue'
        });

        //.a와.b의 형제요소들에게만 적용
        $('.a.b').siblings().css({
            'background':'yellow'
        });

        //.a.b의 부모요소
        $('.a.b').parent().css({
            'border':'2px solid green'
        })
  </script>
</body>

 

 

[  jQuery 응용 해보기 - 4 next(), prev() 함수 ]

<head>
</head>
<body>
<div class="parent">
    <div class="ch1">One</div>
        <div>Two</div>
        <div>Three</div>
    <div id="ch2">Four</div>
        <div>Five</div>
        <div>Six</div>
    <div class="ch3">Seven</div>
  </div>
  <script>
        $('#ch2').next().css('background-color','yellow'); //#ch2는 four인데 next를 사용하여 Five에 적용
        $('#ch2').nextAll().css('background-color','yellow'); //#ch2인 four를 기준으로 next 모두에 적용 Five,Six,Seven

        $('#ch2').prev().css('background-color','pink'); //#ch2인 four를 기준으로 이전것 Three에 적용
        $('#ch2').prevAll().css('background-color','pink'); //#ch2인 four를 기준으로 이전것 모두에 적용 Three,Two,One

        $('#ch2').nextUntil('.ch3').css('background-color','orange'); //ch2를 기준으로 ch3가 나올때 까지 Five, Six
        $('#ch2').prevUntil('.ch3').css('background-color','orange'); //ch2를 기준으로 ch3가 나올때 까지 Three,Two,One
  </script>
</body>

참고만 하기 이런 식이다 ~ 왜냐면 주석처리 안 해서 다 겹쳐졌거든 !!

 

[  jQuery 응용 해보기 - 5 eq(index), 요소:first-child, 요소:last-child, 요소-nth-child 함수 ]

<head>
  <style>
    .di div{
        border: 2px solid tomato;
        width: 100px;
        height: 100px;
        display: inline-block;
    }
  </style>
</head>
<body>
<div class="di">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>
  <script>
        //eq(index(2)) 즉 3번째 박스를 뜻함
        $('.di div').eq(2).css('background-color','red');

        //nth-child() 2번째 자식 즉 2번째 박스를 뜻함
        $('.di div:nth-child(2)').css('background-color','blue');

        //first-child 첫번째 자식 즉 첫번째 박스를 뜻함
        $('.di div:first-child').css('background-color','yellow');

        //last-child 마지막 자식 즉 다섯번째 박스를 뜻함
        $('.di div:last-child').css('background-color','pink');
  </script>
</body>

 

[  jQuery 응용 해보기 - 6 요소:gt(index),요소:lt(index),문서객체.not('선택자'),문서객체.has('선택자') 함수 ]

  gt(<) : 선택된 인덱스부터 다음의 모든 요소 선택

  lt(>) : 선택된 인덱스부터 이전의 모든 요소 선택

  not() : 선택자 제외하고(=이외) 모든 요소 선택

  has() : 선택요소를 포함(has)한 요소만 선택

<head>
  <style>
    .di div{
        border: 2px solid tomato;
        width: 100px;
        height: 100px;
        display: inline-block;
        vertical-align: middle; /* 마지막 박스만 삐둘어져서 추가한 코드 */
    }
  </style>
</head>
<body>
<div class="di">
    <div></div>
    <div></div>
    <div class="target"></div>
    <div></div>
    <div><span>span</span></div>
</div>
  <script>
        //gt는 부등호 기호 : 선택된 인덱스부터 다음의 모든 요소 선택 = 초과 3 < x
        $('.di div:gt(2)').css('background-color','yellow');

        //lt는 부등호 기호 : 선택된 인덱스부터 이전의 모든 요소 선택 = 미만 3 > x
        $('.di div:lt(2)').css('background-color','pink');

        //not은 target을 제외하고 나머지 모두 선택
        $('.di div').not('.target').css('background-color','aqua');

        //has는 span 현재칸 요소만 선택하겠다
        $('.di div').has('span').css('background-color','violet');
  </script>
</body>

참고만 하기 이런 식이다 ~ 왜냐면 주석처리 안 해서 다 겹쳐졌거든 !!

 

 

[  jQuery 응용 해보기 - 7 이벤트 처리 addClass, removeClass, toggleClass 버튼 클릭 ]

<head>
  <style>
  </style>
</head>
<body>
    <div class="di">
        <button class="btn a">add</button>
        <button class="btn re active">remove</button>
        <button class="btn toggle">toggle</button>
      </div>
  <script>
        $('.a').click(function() { //add버튼 클릭시
            $(this).addClass('active'); //active라는 클래스 추가
        })
        $('.re').click(function() {
            $(this).removeClass('active'); //active라는 클래스 삭제
        })
        $('.toggle').click(function(){
            $(this).toggleClass('active'); //active라는 클래스 추가삭제 반복 됨
        })
  </script>
</body>

 

<head>
  <style>
    .size button.act{
        background-color: red;
        color: white;
    }
  </style>
</head>
<body>
    <div class="di">
        <h2>신발 사이즈 선택</h2>
        <div class="size">
            <button>225</button>
            <button>230</button>
            <button>235</button>
            <button>240</button>
            <button>245</button>
            <button>250</button>
        </div>
    </div>
  <script>
        $('.size button').click(function() {
            $(this).addClass('act');
            $(this).siblings().removeClass('act');
        });
  </script>
</body>

 

 

 

 

 

 

[ alt + shift + 방향키 아래 or 위 ] -> 복사

 

728x90