Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách chuyển HashMap sang JSON dùng GSON trong Android

Giới thiệu

GSON là thư viện Google chuyển đổi đối tượng Java ↔ JSON. Ví dụ này serialize HashMap thành chuỗi JSON.

Bước 1: Tạo project mới

Android Studio → File → New Project.

Bước 2: Thêm dependency GSON (build.gradle)

dependencies {
    implementation 'com.google.code.gson:gson:2.10.1' // phiên bản mới
    // các dependency khác...
}

Bước 3: Giao diện (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="Kết quả JSON"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Bước 4: MainActivity.java

package com.example.andy.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.google.gson.Gson;
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 map = new HashMap<>();
        map.put("JAVA", "NetBeans");
        map.put("Android", "Android Studio");
        map.put("Kotlin", "Notepad++");

        Gson gson = new Gson();
        String json = gson.toJson(map); // Chuyển Map → JSON
        result.setText(json);
    }
}

Kết quả JSON

{
  "JAVA": "NetBeans",
  "Android": "Android Studio",
  "Kotlin": "Notepad++"
}

Chạy ứng dụng

TextView hiển thị chuỗi JSON từ HashMap.

Cách chuyển HashMap sang JSON dùng GSON trong Android