Gson 사용방법

com.google.gson.Gson

 

 

 

Gson은 java 에서 json 데이터를 다루기 위해 사용될 수 있는 라이브러리 중 하나입니다. 구글(Google)에서 만들었고, 주로 파싱(Parsing)을 할 때 사용되는 라이브러리입니다. 이 라이브러리를 사용해서 json 문자열을 object로 변경시키거나 반대로, object를 json 문자열로 변경시킬 수 있습니다.

 

 

사용시 주의할 점은

  • object를 String으로 변환할 때, null 값에 대해서 변환 여부를 조절할 수 있다. (=GsonBuilder().serializeNulls() 사용)
  • object를 String으로 변환할 때, 순서는 보장받지 못한다. (=순서까지 고려해야한다면 다른 방법을 추가로 사용) 

 

Class와 String간의 변환

Class 준비 (변환에 사용될 대상인 샘플 Class)

class Joker {
	public int item1;
	public String item2;
	public String item3;
}

 

1. Class -> json String

public void toJsonTest() {
	Joker joker = new Joker();
	joker.item1 = 100;
	joker.item2 = null;
	joker.item3 = "hello";
		
	// not include null
	{
		Gson gson = new Gson();
		String json = gson.toJson(joker);
		System.out.println(json);
	}		
		
	// include null
	{
		Gson gson = new GsonBuilder().serializeNulls().create();
		String json = gson.toJson(joker);
		System.out.println(json);
	}
}

출력 결과 :

{"item1":100,"item3":"hello"}

{"item2":null,"item1":100,"item3":"hello"}

 

2. json String -> Class

public void fromJsonTest() {
	String json = "{\"item1\":100,\"item3\":\"hello\"}";
		
	Gson gson = new Gson();
	Joker joker = gson.fromJson(json, Joker.class);
	System.out.println(joker.item1);
	System.out.println(joker.item2);
	System.out.println(joker.item3);
}

출력 결과 :

100

null

hello

 

 

Map과 String간의 변환

1. Map -> json String

public void toJsonTest() {
	Map<String, Object> map = new HashMap<String, Object>(); 
	map.put("item1", 100);
	map.put("item2", null);
	map.put("item3", "hello");
		
	// not include null
	{
		Gson gson = new Gson();
		String json = gson.toJson(map);
		System.out.println(json);
	}		
		
	// include null
	{
		Gson gson = new GsonBuilder().serializeNulls().create();
		String json = gson.toJson(map);
		System.out.println(json);
	}
}

출력 결과 :

{"item1":100,"item3":"hello"}

{"item1":100,"item2":null,"item3":"hello"}

 

2. json String -> Map

public void fromJsonTest() {
	String json = "{\"item1\":100,\"item3\":\"hello\"}";
		
	Gson gson = new Gson();
	Type listType = new TypeToken<HashMap<String, Object>>(){}.getType();
	Map<String, Object> joker = gson.fromJson(json, listType);
	System.out.println(joker.get("item1"));
	System.out.println(joker.get("item2"));
	System.out.println(joker.get("item3"));
}

출력 결과 :

100.0

null

hello

 

 

참고 사이트

Google Gson 깃 허브

https://github.com/google/gson

 

Gson 사용 가이드

https://sites.google.com/site/gson/gson-user-guide