Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีแปลง HashMap เป็น JSON ด้วย GSON ใน Android

GSON เป็นไลบรารี Java ใช้แปลง Object เป็น JSON และ JSON กลับเป็น Object ทำงานภายในผ่านกระบวนการ Serialization และ Deserialization

ตัวอย่างการแปลง HashMap เป็น JSON ด้วย GSON Library

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio ไปที่ File → New Project แล้วกรอกรายละเอียดที่จำเป็นเพื่อสร้างโปรเจกต์ใหม่

ขั้นตอนที่ 2: เพิ่ม Dependency ใน 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'
    // เพิ่ม GSON library ล่าสุด
    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'
}

ในโค้ดด้านบน เราได้เพิ่ม GSON library เวอร์ชันล่าสุด

ขั้นตอนที่ 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"
        android:layout_marginTop="100dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

ในโค้ดด้านบน เราเพิ่ม TextView เพื่อแสดงผลลัพธ์ JSON

ขั้นตอนที่ 4: เขียนโค้ด MainActivity.java

package com.example.andy.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
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 และเพิ่มข้อมูล
        HashMap hashMap = new HashMap<>();
        hashMap.put("JAVA", "NetBeans");
        hashMap.put("Android", "Android Studio");
        hashMap.put("Kotlin", "Notepad++");
        
        // แปลง HashMap เป็น JSON ด้วย GSON
        Gson gson = new Gson();
        String jsonData = gson.toJson(hashMap);
        
        // แสดงผลใน TextView
        result.setText(jsonData);
    }
}

การทดสอบแอปพลิเคชัน

เชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์ ใน Android Studio เปิดไฟล์ Activity และคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณ แล้วตรวจสอบหน้าจอเริ่มต้น

วิธีแปลง HashMap เป็น JSON ด้วย GSON ใน Android

ผลลัพธ์จะแสดง HashMap ในรูปแบบ JSON: {"JAVA":"NetBeans","Android":"Android Studio","Kotlin":"Notepad++"}