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

jihun Choi·2023년 5월 14일
0
post-thumbnail

😎 Gson이란?

Gson은 json을 파싱하고 생성하기 위해 사용하는 구글에서 개발한 오픈소스입니다 java object를 Json 문자열로 변환할수 있습니다

😎 Gson 의존성 추가

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

gson을 사용하기 위해서는 gson 의존성을 추가해줘야 합니다

😎 Gson 객체 생성

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

new Gson()
new GsonBuilder.create()

2가지 방법으로 객체를 선언 할수 있습니다

😎 json -> string 으로 변환

     Gson gson = new Gson();
	 JsonObject jsonObject = new JsonObject();
     jsonObject.addProperty("name", "hello");
     jsonObject.addProperty("id", 1234);

     String result = gson.toJson(jsonObject);
     //result : {"name":"hello","id":1234}
     System.out.println(result);

toJson 메소드를 통해 JsonObject를 string으로 변환할수 있습니다

😎 object -> json 으로 변환

  • Customer 오브젝트 생성
	@Getter @Setter
    public class Customer {

    	private String custname;
    	private int age;
    
    }
  • Cusomer 오브젝트 json으로 변환
     Gson gson = new Gson();
	 Customer customer = new Customer();
     customer.setAge(3);
     customer.setCustname("jh");

     String result = gson.toJson(object);
     //result : {"custname":"jh","age":3}
     System.out.println(result);
     

toJson 메소드를 통해 Object객체를 json으로 변환할수 있습니다

😎 json -> object 으로 변환

  • Customer 오브젝트 생성
	@Getter @Setter
    public class Customer {

    	private String custname;
    	private int age;
    
    }
  • json -> object로 변환
	Gson gson = new Gson();
	String json = "{age:1,custname:jh}";

    Customer customer = gson.fromJson(json, Customer.class);

    System.out.println(customer.getAge());
    System.out.println(customer.getCustname());

fromJson 메소드를 통해 json을 object로 변환할수 있습니다
fromJson은 String과 객체.class 파라미터를 가집니다

😎 map -> json 으로 변환

    Gson gson = new Gson();
	Map<String, String> map = new HashMap<>();
    map.put("name","jh");
    map.put("age", "123");

    String result = gson.toJson(map);
    System.out.println(result);

toJson 메소드를 통해 map객체를 json으로 변환할수 있습니다

😎 json -> map 으로 변환

    Gson gson = new Gson();
	String json = "{'age':'1','custname':'jh'}";

    Map<String, Object> map = gson.fromJson(json, Map.class);

    for(Map.Entry<String, Object> entry : map.entrySet()){
        System.out.println(entry.getKey() + " : " + entry.getValue());
    }

fromJson 메소드를 통해 json을 map로 변환할수 있습니다
fromJson은 String과 Map.class 파라미터를 가집니다

😎 값이 null인 필드의 json property 생성

    Gson gsonNullObejct = new GsonBuilder().serializeNulls().create();
	JsonObject jsonObject = new JsonObject();
    jsonObject.add("name", null);
    jsonObject.addProperty("age", 9);

    String result = gsonNullObejct.toJson(json);

    System.out.println(result);

new GsonBuilder().serializeNulls().create()로 Gson 객체를 생성하여 value가 null일때도 json property가 생성될수 있도록 할수있습니다

profile
성장을 위해 열심히 노력하는 개발자 입니다

0개의 댓글