관리자 글쓰기

1. Gson이란

Gson은 Java에서 Json을 파싱하고, 생성하기 위해 사용되는 구글에서 개발한 오픈 소스다.

Java Object를 Json 문자열로 변환할 수 있고, Json 문자열을 Java Object로 변환할 수 있다.

 

2. Gson 라이브러리 추가하기 

Maven

JSON 파싱에 사용할 json-simple 라이브러리를 추가하기 위해

pom.xml 파일에 아래와 같이 dependency를 추가한다.

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

 

Gradle

dependencies {
  implementation 'com.google.code.gson:gson:2.8.7'
}

 

직접추가도 가능

https://search.maven.org/artifact/com.google.code.gson/gson/2.8.7/jar

 

Maven Central Repository Search

 

search.maven.org

해당 링크에서 jar를 직접 다운받고, 라이브러리에 추가 가능

 

3. Gson 객체 생성하기

Gson 객체를 생성하는 방법은 2가지가 있다.

new Gson()

new GsonBuilder.create()

 

new GsonBuilder() 을 이용하여 Gson 객체를 생성하면, 몇가지 옵션을 추가해서 객체를 생성할 수 있다.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
 
public class CreateGson {
    public static void main(String[] args) {
        
        // new
        Gson gson1 = new Gson();
 
        // GsonBuilder
        Gson gson2 = new GsonBuilder().create();
        Gson gson3 = new GsonBuilder().setPrettyPrinting().create();
        
    }
}

 

4. Json 생성하기

import com.google.gson.Gson;
import com.google.gson.JsonObject;
 
public class GsonExample {
 
    public static void main(String[] args) {
 
        Gson gson = new Gson();
 
        // Json key, value 추가
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("name", "anna");
        jsonObject.addProperty("id", 1);
 
        // JsonObject를 Json 문자열로 변환
        String jsonStr = gson.toJson(jsonObject);
 
        // 생성된 Json 문자열 출력
        System.out.println(jsonStr); // {"name":"anna","id":1}
        
    }
}

jsonObject.addProperty("name", "anna");

JsonObject 객체를 생성하여, 

이 객체에 프로퍼티를 추가한다