Directory
1. Introduction to Gson
2. How to use
Full code:
MainActivity:
layout:
operation result:
1. Introduction to Gson
Gson is a Java library provided by Google for converting Java objects into JSON format data or converting JSON format data into Java objects.
Common methods:
Method name | Function |
toJson(Object src) | Convert the object into corresponding JSON data |
fromJson(String json,Class< T> classOT) | Convert JSON data into objects |
2. How to use
Gson is an open source library provided by Google for converting Java objects to and from JSON data. The following is the detailed method of using Gson:
1. Add dependencies
In your Android project, you need to add the following dependencies to the build.gradle file:
dependencies {
implementation ‘com.google.code.gson:gson:2.8.7’
}
2. Create a Java class
First, you need to create a Java class that will convert to and from JSON objects. The following sample code shows the basic structure of a Java class:
package com.example.gsondemo; public class Student { private String id; private String name; private int age; private String sex; public String getSex() { return sex; } public void setSex(String sex) { this. sex = sex; } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this. age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
3. Convert a Java object to a JSON string
Use Gson to serialize Java objects into JSON strings. The following sample code shows how to use Gson to convert a User object to a JSON string:
Student student = new Student(); student.setId("001"); student.setName("xiaoming"); student. setAge(18); student.setSex("male"); // convert the object into json data String jsonStr = gson.toJson(student);
4. Convert JSON string to Java object
Use Gson to deserialize JSON strings to Java objects. The following sample code shows how to use Gson to convert a JSON string to a User object:
// convert the object into json data String jsonStr = gson.toJson(student); // parse json into object data Student s = gson.fromJson(jsonStr,Student.class); et5.setText(s.getId() + " " + s.getName() + " " + s.getAge() + " " + s.getSex());
Through the above steps, you can use Gson to easily convert Java objects and JSON data to and from each other.
Full code:
MainActivity:
package com.example.gsondemo; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends AppCompatActivity { Button btn; EditText et1,et2,et3,et4,et5; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R. layout. activity_main); initView(); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Gson gson = new Gson(); Student student = new Student(); student.setId("001"); student.setName("xiaoming"); student. setAge(18); student.setSex("male"); // convert the object into json data String jsonStr = gson.toJson(student); et1.setText(jsonStr); // second list data List<String> list = Arrays.asList("1","ad","12","134"); et2.setText(gson.toJson(list)); // The third mapping object Map<String,Object> content = new HashMap<>(); content. put("id","002"); content.put("name","xiaohua"); content.put("sex","female"); content. put("age",18); et3.setText(gson.toJson(content)); // Use GSON's fromJson method // Parsing complex data requires Type to parse or generate JSON data. Type type = new TypeToken<ArrayList<String>>(){}.getType(); ArrayList<String> sList = gson.fromJson(list.toString(),type); et4.setText(sList.toString()); // parse json into object data Student s = gson.fromJson(jsonStr,Student.class); et5.setText(s.getId() + " " + s.getName() + " " + s.getAge() + " " + s.getSex()); } }); } private void initView() { btn = findViewById(R.id.btn); et1 = findViewById(R.id.et1); et2 = findViewById(R.id.et2); et3 = findViewById(R.id.et3); et4 = findViewById(R.id.et4); et5 = findViewById(R.id.et5); } }
Layout:
<?xml version="1.0" encoding="UTF-8"?> <LinearLayout android:paddingTop="16dp" android:paddingRight="16dp" android:paddingLeft="16dp" android:paddingBottom="16dp" android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android"> <Button android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@ + id/btn" android:layout_alignParentTop="true" android:text="GSON TEST"/> <EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@ + id/et1" android:text="FromObjectToJsonData" android:layout_below="@ + id/textView1" android:layout_marginTop="11dp" android:inputType="textPersonName"/> <EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@ + id/et2" android:text="FromListDataToJsonData" android:layout_below="@ + id/et1" android:inputType="textPersonName" android:ems="10"/> <EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@ + id/et3" android:text="FromMapDataToJsonData" android:layout_below="@ + id/et2" android:layout_marginTop="11dp" android:inputType="textPersonName"/> <EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@ + id/et4" android:layout_alignParentStart="true" android:layout_alignParentLeft="true" android:text="FromJsonToComplexData" android:layout_below="@ + id/textView2" android:inputType="textPersonName" android:ems="10"/> <EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@ + id/et5" android:layout_alignParentStart="true" android:layout_alignParentLeft="true" android:text="FromJsonToObjectData" android:layout_below="@ + id/textView2" android:ems="10"/> </LinearLayout>
Student is on it.