如何在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数据。
点击此处下载项目代码
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP