본문 바로가기
Tech/Java

Gson을 이용한 json 변환 예제

by Augustine™ 2020. 2. 20.
반응형

json의 Object 변환, Object의 json 으로 변환할 때, Gson을 써보자.

먼저 pom.xml 에 아래 라이브러리를 추가한다.

	    <dependency>
	        <groupId>com.google.code.gson</groupId>
	        <artifactId>gson</artifactId>
	        <version>2.2.4</version>
	    </dependency>	

 

아래는 Gson을 이용한 변환 예제

package com.augustine.ctrl;

import com.augustine.jpa.domain.Member;
import com.google.gson.Gson;

public class GsonExample {

	public static void main(String[] args) {
		
		//Example for From Json to Object
		String jsonStr = "{'name' : 'augustine', 'address' : 'Seoul city', "
				+ " 'level' : 'member'}";

		Gson gson = new Gson();
		Member member = gson.fromJson(jsonStr,  Member.class);
		
		System.out.println("Name is == " +member.getName());		
		System.out.println("Address is == " +member.getAddress());
		System.out.println("Level is == " +member.getLevel());
		
		
		//Example for From Object to Json
		Member member2 = new Member();
		member2.setName("Rubin");
		member2.setAddress("NewYork");
		member2.setLevel("Manager");
		
		System.out.println("\n\n\n\n");
		System.out.println(gson.toJson(member2));
		
	}
	
	
}
반응형

'Tech > Java' 카테고리의 다른 글

Overriding와 Overloading  (0) 2019.08.25
Java command line의 Arguments에 대해 알아보기  (2) 2019.08.13
Abstract Factory Design Pattern  (0) 2019.03.20
Factory Design Pattern  (0) 2019.03.18
Singleton Design Pattern  (0) 2019.03.14

댓글