GSON이란?
GSON은 자바(Java) 라이브러리로, 객체(Object)를 JSON으로 변환하거나 반대로 JSON을 객체로 변환할 때 사용됩니다. 내부적으로는 직렬화(Serialization)와 역직렬화(Deserialization) 원리를 기반으로 동작합니다.
이 글에서는 GSON 라이브러리를 활용해 HashMap을 JSON으로 변환하는 과정을 단계별로 살펴보겠습니다.
1단계: 새 프로젝트 만들기
Android Studio에서 새 프로젝트를 생성합니다. 상단 메뉴에서 File → New Project로 이동한 뒤, 프로젝트 생성에 필요한 모든 항목을 입력합니다.
2단계: build.gradle에 GSON 라이브러리 추가
build.gradle 파일에 아래 코드를 추가합니다.
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.andy.myapplication"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}위 코드의 dependencies 항목에 최신 버전의 GSON 라이브러리(gson:2.8.5)를 추가했습니다.
3단계: 레이아웃 파일 작성
res/layout/activity_main.xml에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/result" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Result Data" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>
위 코드에는 변환 결과를 화면에 표시할 TextView 하나를 추가했습니다.
4단계: MainActivity 작성
src/MainActivity.java에 아래 코드를 추가합니다.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView result=findViewById(R.id.result);
HashMap<String,String> hashMap=new HashMap<>();
hashMap.put("JAVA","NetBeans");
hashMap.put("Android","Android Studio");
hashMap.put("Kotlin", "Notepad ++");
Gson gson=new Gson();
String MapData=gson.toJson(hashMap);
result.setText(MapData);
}
}코드 흐름을 간단히 설명하면 다음과 같습니다. 먼저 언어 이름과 해당 개발 도구를 담은 HashMap을 생성하고, Gson 인스턴스의 toJson() 메서드를 호출해 Map 전체를 JSON 문자열로 변환한 후, 그 결과를 TextView에 출력합니다.
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 앱을 실행하려면 프로젝트의 액티비티 파일 중 하나를 열고 툴바의 Run 아이콘을 클릭하세요.
목록에서 본인의 모바일 기기를 선택한 뒤, 기기 화면에 아래와 같은 기본 화면이 표시되는지 확인합니다.

위 출력 결과에서 HashMap이 JSON 형태의 데이터로 성공적으로 변환되어 표시되는 것을 확인할 수 있습니다.