jowoohyeong / TIGENSOFT

0 stars 0 forks source link

22.12.23금<Gson> #5

Open jowoohyeong opened 1 year ago

jowoohyeong commented 1 year ago

Gson 라이브러리 사용법 및 예제

Gson은 Java에서 Json을 파싱하고, 생성하기 위해 사용되는 구글에서 개발한 오픈소스 Java Object를 Json 문자열로 변환하고, 다시 변환도 가능하다.

jowoohyeong commented 1 year ago

Gson 라이브러리 추가

Maven

<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'
}
jowoohyeong commented 1 year ago
public class Test {
    private String name;
    private int id;

    public Test(String name, int id) {
        this.name = name;
        this.id = id;
    } 
}

Gson 객체 생성

  1. new Gson()

    import com.google.gson.Gson;
    import com.google.gson.JsonObject;
    public class GsonExample {
    
    public static void main(String[] args) {
        Gson gson = new Gson();
        Test test = new Test("jo", 1);
    
        String str1 = gson.toJson(test);
    
        JsonObject jO = new JsonObject();
        jO.addProperty("name", "jo2");
        jO.addProperty("id", 2);
    
        String str2 = gson.toJson(jO);   //Json 문자열으로 변환
    
        System.out.println(str1);        //output : {"name:""jo1", "id":1}
        System.out.println(str2);        //output : {"name":"jo2", "id":2}
    }
    }

https://hianna.tistory.com/629