본문 바로가기
안드로이드 자바

[JAVA][Android]Gson 라이브러리 활용하여 JSON 문자열 다루기

by teamnova 2024. 6. 19.

오늘은 Gson 라이브러리를 활용해 JSON 문자열 데이터를 다루는 예제를 보여드리겠습니다.

 

 

 

 

라이브러리 추가

build.gradle(module) 의 dependency 내부에 Gson 라이브러리를 추가합니다. gradle 사용 환경에 맞춰 입력하세요.

또는

 

 

=> Gson 라이브러리 버전은 아래링크에서 확인해 주세요

https://github.com/google/gson

 

 

레이아웃 xml 파일 코드(activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp">

        <EditText
            android:id="@+id/editTextName1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="이름 입력" />

        <EditText
            android:id="@+id/editTextAge1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="나이 입력"
            android:inputType="number"/>

        <Button
            android:id="@+id/buttonToJsonUser"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="JSON 문자열로 변환하기(User 클래스 활용)"/>

        <TextView
            android:id="@+id/textViewResultUser"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:layout_marginTop="10dp"/>

        <Button
            android:id="@+id/buttonFromJsonUser"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="JSON 문자열 파싱하기(User 클래스 활용)"
            android:layout_marginTop="10dp"/>

        <TextView
            android:id="@+id/textViewStatusUser"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:textColor="#B1AEAE"
            android:textStyle="bold"
            android:text="JSON 문자열 파싱 결과(User 클래스 활용)"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/textViewNameUser"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:layout_marginTop="10dp"/>

        <TextView
            android:id="@+id/textViewAgeUser"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:layout_marginTop="10dp"/>

        <View
            android:layout_width="match_parent"
            android:layout_height="3dp"
            android:background="#00E2FF"
            android:layout_marginTop="10dp"/>
        <EditText
            android:id="@+id/editTextName2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="이름 입력"
            android:layout_marginTop="10dp"/>

        <EditText
            android:id="@+id/editTextAge2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="나이 입력"
            android:inputType="number"/>

        <Button
            android:id="@+id/buttonToJsonJson"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="JSON 문자열로 변환하기(JsonObject 활용)"/>

        <TextView
            android:id="@+id/textViewResultJson"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:layout_marginTop="10dp"/>

        <Button
            android:id="@+id/buttonFromJsonJson"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="JSON 문자열 파싱하기(JsonParser 활용)"
            android:layout_marginTop="10dp"/>

        <TextView
            android:id="@+id/textViewStatusJson"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:textStyle="bold"
            android:text="JSON 문자열 파싱 결과(JsonParser 활용)"
            android:textColor="#B1AEAE"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/textViewNameJson"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:layout_marginTop="10dp"/>

        <TextView
            android:id="@+id/textViewAgeJson"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:layout_marginTop="10dp"/>
    </LinearLayout>
</ScrollView>

 

 

 

 

User 클래스 자바 파일 코드 (JSON 직렬화 또는 역직렬화시 활용할 자바 클래스)

public class User {
    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

 

 

 

 

 

 

액티비티 자바 코드

public class MainActivity extends AppCompatActivity {
    // User 클래스, toJson, fromJson 활용 관련 변수들
    private EditText editTextName1, editTextAge1;
    private TextView textViewResultUser,textViewNameUser, textViewAgeUser;
    private Button buttonToJsonUser, buttonFromJsonUser;


    // JsonObject, JsonParser 활용 관련 변수들
    private EditText editTextName2, editTextAge2;
    private TextView textViewResultJson,textViewNameJson, textViewAgeJson;
    private Button buttonToJsonJson, buttonFromJsonJson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 첫 번째 사용자 입력 관련 뷰들(User 클래스, toJson, fromJson 활용)
        editTextName1 = findViewById(R.id.editTextName1);
        editTextAge1 = findViewById(R.id.editTextAge1);
        textViewResultUser = findViewById(R.id.textViewResultUser);
        textViewNameUser = findViewById(R.id.textViewNameUser);
        textViewAgeUser = findViewById(R.id.textViewAgeUser);
        buttonToJsonUser = findViewById(R.id.buttonToJsonUser);
        buttonFromJsonUser = findViewById(R.id.buttonFromJsonUser);

        // 두 번째 사용자 입력 관련 뷰들(JsonObject, JsonParser 활용)
        editTextName2 = findViewById(R.id.editTextName2);
        editTextAge2 = findViewById(R.id.editTextAge2);
        textViewResultJson = findViewById(R.id.textViewResultJson);
        textViewNameJson = findViewById(R.id.textViewNameJson);
        textViewAgeJson = findViewById(R.id.textViewAgeJson);
        buttonToJsonJson = findViewById(R.id.buttonToJsonJson);
        buttonFromJsonJson = findViewById(R.id.buttonFromJsonJson);

        // User 클래스를 활용하여 JSON 문자열 생성
        buttonToJsonUser.setOnClickListener(v -> {
            String name = editTextName1.getText().toString();
            int age = Integer.parseInt(editTextAge1.getText().toString());
            User user = new User(name, age);
            Gson gson = new Gson();
            String json = gson.toJson(user);
            textViewResultUser.setText(json);
        });

        // User 클래스를 활용하여 JSON 문자열 파싱
        buttonFromJsonUser.setOnClickListener(v -> {
            String json = textViewResultUser.getText().toString();
            Gson gson = new Gson();
            User user = gson.fromJson(json, User.class);
            textViewNameUser.setText("이름: " + user.getName());
            textViewAgeUser.setText("나이: " + user.getAge());
        });

        // JsonObject를 활용하여 JSON 문자열 생성
        buttonToJsonJson.setOnClickListener(v -> {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("name", editTextName2.getText().toString());
            jsonObject.addProperty("age", Integer.parseInt(editTextAge2.getText().toString()));
            textViewResultJson.setText(jsonObject.toString());
        });

        // JsonParser를 활용하여 JSON 문자열 파싱
        buttonFromJsonJson.setOnClickListener(v -> {
            String json = textViewResultJson.getText().toString();
            JsonElement jsonElement = JsonParser.parseString(json);
            if (jsonElement.isJsonObject()) {
                JsonObject obj = jsonElement.getAsJsonObject();
                String name = obj.get("name").getAsString();
                int age = obj.get("age").getAsInt();
                textViewNameJson.setText("이름: " + name);
                textViewAgeJson.setText("나이: " + age);
            }
        });
    }
}

 

 

 

 

실행 영상

 

 

 

 

1. 미리 정의한 클래스(User 클래스) 활용

2.JsonObject 와 JsonParser 활용

두가지 방법으로 JSON 문자열 생성, 파싱하는 예시를 만들었습니다.

이 방법들 외 JsonReader, JsonWriter 등 Gson 라이브러리는 다양한 방식으로 Json 데이터를 다룰 수 있게 편의를 제공해줍니다.