투케이2K

366. (java/자바) gson 사용해 모델 클래스 객체를 json 변환 및 json 데이터를 모델 객체로 매핑 수행 - Model Class To Json 본문

Java

366. (java/자바) gson 사용해 모델 클래스 객체를 json 변환 및 json 데이터를 모델 객체로 매핑 수행 - Model Class To Json

투케이2K 2026. 3. 10. 19:14
728x90
반응형

[개발 환경 설정]

개발 툴 : AndroidStudio

개발 언어 : Java

 

[소스 코드]

// --------------------------------------------------------------------------------------
[개발 및 테스트 환경]
// --------------------------------------------------------------------------------------

- 언어 : Java / Kotlin


- 개발 툴 : AndroidStudio


- 구분 : 간단 소스 / gson / model class / json


- 사전) 👉 GSON 간략 설명 : 

  >> GSON 은 자바 객체를 JSON 표현으로 변환하는 데 사용할 수 있는 자바 라이브러리 입니다

  >> GSON 은 구글에서 만들었으며, Apache 2.0 license 를 포함 합니다

  >> gradle 을 사용해 gson 객체 의존성 설정 방법 : 

    - implementation 'com.google.code.gson:gson:2.8.6'


- 사전) 👉 get/set 모델 클래스 간략 설명 : 

  >> get/set 모델 클래스는 객체지향(OOP) 에서 모델(Model) 클래스의 필드(상태) 에 접근할 때 사용하는 게터(getter)와 세터(setter)를 의미합니다.

  >> get/set을 쓰는 이유 : 

    - 유효성 검증 : 잘못된 값이 들어오는 것을 막음
    - 불변성(immutability) 유지 : 생성 후 바뀌면 안 되는 값은 getter만 허용
    - 부수효과(side effects) 관리 : 값 변경 시, 이벤트/로그/캐시 무효화 등 추가 처리 가능
    - 인터페이스 안정성 : 내부 구현(필드명·구조) 변경 시에도 외부 코드는 메서드 시그니처만 유지하면 안전
    - 지연 계산/캐싱 : get 시점에 값을 계산하거나 캐시해둘 수 있음(Computed/Derived Property)

// --------------------------------------------------------------------------------------






// --------------------------------------------------------------------------------------
[소스 코드]
// --------------------------------------------------------------------------------------

// -------------------------------------------------------------
// 🟡 [get/set 클래스 생성] : M_Person
// -------------------------------------------------------------
package com.example.javaproject;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;
import java.util.HashMap;

public class M_Person {


     // ------------------------------------
     // TODO [클래스 설명]
     // ------------------------------------
     // 1. GSON 모델 클래스
     // ------------------------------------
     // 2. @SerializedName : JSON 객체 생성 시 표시될 key name
     // ------------------------------------
     // 3. @Expose : 데이터가 null 일 경우 json 생성 시 제외 설정
     // ------------------------------------
     // 4. build.gradle 설정 : implementation 'com.google.code.gson:gson:2.8.6'
     // ------------------------------------     





    // ------------------------------------
    // TODO [전역 변수 선언]
    // ------------------------------------
    private static final String ACTIVITY_NAME = "M_Person";





    // ------------------------------------
    // TODO [클래스 생성자 초기화]
    // ------------------------------------
    public M_Person(String name, int age, Note note, ArrayList<Item> items){
        this.name = name;
        this.age = age;
        this.note = note;
        this.items = items;
    }





    // ------------------------------------
    // TODO [JSON KEY DATA]
    // ------------------------------------

    // [JSON KEY]
    @SerializedName("key_name") public String name;
    

    // [JSON KEY]
    @SerializedName("key_age") public int age;
    

    // [JSON KEY]
    @SerializedName("key_note") public Note note;
    

    // [JSON KEY]
    @SerializedName("key_item") public ArrayList<Item> items;
    

    // [JSON OBJECT]
    public static class Note {

        public Note(String blog){
            this.blog = blog;
        }

        @SerializedName("key_blog") public String blog;
    }
    

    // [JSON ARRAY]
    public static class Item {

        public Item(String lang, String tool){
            this.lang = lang;
            this.tool = tool;
        }

        @SerializedName("key_lang") public String lang;
        @SerializedName("key_tool") public String tool;
    }


} // TODO [클래스 종료]



// -------------------------------------------------------------
// 🔵 [Json To Class] Json 데이터를 모델 클래스에 매핑 수행
// -------------------------------------------------------------

// [String 샘플 JSON 데이터 생성]
String sampleJson = "{\"key_age\":30,\"key_item\":[{\"key_lang\":\"Kotlin\",\"key_tool\":\"Android\"},{\"key_lang\":\"Swift\",\"key_tool\":\"Xcode\"}],\"key_name\":\"투케이\",\"key_note\":{\"key_blog\":\"twok.blog\"}}";


// [M_Person 클래스 생성 실시]
M_Person m_person = new Gson().fromJson(sampleJson, M_Person.class);


// [M_Person 클래스에 매핑된 데이터 확인]
String name = m_person.name;
int age = m_person.age;

String note = new Gson().toJson(m_person.note);
String items = new Gson().toJson(m_person.items);



// -------------------------------------------------------------
// 🔵 [Class To Json] 모델 클래스 데이터를 Json 데이터로 변환 수행
// -------------------------------------------------------------

// [String 샘플 JSON 데이터 생성]
String sampleJson = "{\"key_age\":30,\"key_item\":[{\"key_lang\":\"Kotlin\",\"key_tool\":\"Android\"},{\"key_lang\":\"Swift\",\"key_tool\":\"Xcode\"}],\"key_name\":\"투케이\",\"key_note\":{\"key_blog\":\"twok.blog\"}}";


// [M_Person 클래스 생성 실시]
M_Person m_person = new Gson().fromJson(sampleJson, M_Person.class);


// [M_Person 클래스 데이터를 JSON 으로 변환 수행]
String formatJson = new Gson().toJson(m_person).toString();

// --------------------------------------------------------------------------------------






// --------------------------------------------------------------------------------------
[참고 사이트]
// --------------------------------------------------------------------------------------

[Android] 문법 - [GSON] SerializedName 사용해 모델 클래스 생성 및 response 데이터 자동 파싱 수행 실시

https://kkh0977.tistory.com/3939

https://blog.naver.com/kkh0977/223027624556?trackingCode=blog_bloghome_searchlist


[Observable] [GSON] JsonObject , JsonArray 데이터 Model SerializedName 매핑 및 데이터 확인

https://kkh0977.tistory.com/4019

https://blog.naver.com/kkh0977/223043782135?trackingCode=blog_bloghome_searchlist


[GSON 사용해 Map , Json 데이터 변환 수행 실시]

https://blog.naver.com/kkh0977/222677124966


[라이브러리] [Android] GSON (Java / json / format)

https://blog.naver.com/kkh0977/222914549339?trackingCode=blog_bloghome_searchlist

// --------------------------------------------------------------------------------------
 
728x90
반응형
Comments