如何在Android中使用GSON將HASHMAP轉換為JSON?
GSON是Java庫,用於將物件轉換為JSON以及JSON轉換為物件。在內部,它基於序列化和反序列化工作。
此示例演示如何使用GSON庫將HASHAMP轉換為JSON。
步驟1 - 在Android Studio中建立一個新專案,轉到檔案⇒新建專案,並填寫所有必要的資訊以建立一個新專案。
步驟2 - 在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' }
在上面的程式碼中,我們添加了GSON最新庫。
步驟3 - 將以下程式碼新增到res/layout/activity_main.xml。
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://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,此TextView將顯示結果資料。
步驟4 - 將以下程式碼新增到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); } }
讓我們嘗試執行您的應用程式。我假設您已將您的實際Android移動裝置連線到您的計算機。要從Android Studio執行應用程式,請開啟您的專案之一的活動檔案,然後單擊工具欄中的執行圖示。
選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 -
在上面的輸出中,它顯示了HASHAMP作為JSON資料。
點選此處下載專案程式碼
廣告