


GSON tutorial to implement JSON serialization and deserialization of Java objects
Download GSON from GitHub: https://github.com/google/gson
The application of Gson mainly consists of two conversion functions: toJson and fromJson. Before using this kind of object conversion, you need to create the object category first. And its members can successfully convert the JSON string into the corresponding object.
class Examples { private int answer1 = 100; private String answer2 = "Hello world!"; Examples(){ } // default constructor }
Serialize JAVA object into JSON string
Examples example1 = new Examples(); Gson gson = new Gson(); String json = gson.toJson(example1);
The json result will be
{"answer1":100,"answer2":"Hello world!"}
Deserialize JSON string into corresponding JAVA object
Examples example2= gson.fromJson(json,Examples.class);
==> example2 is the same as example1
Object example1 is serialized into JSON string and passed through toJson , and then declare an object example2 to receive JSON and deserialize it into example2 through fromJson, so example1 is the same as example2
Example:
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; class User{ public User(String name,int age,StringBuffer sex,boolean isChild){ this.name = name; this.age = age; this.sex = sex; this.isChild = isChild; } private String name; private int age; private StringBuffer sex; private boolean isChild; public String toString(){ return "{name="+name+";age="+age+";sex="+sex+";isChild="+isChild+"}"; } public int hashCode(){ return name.hashCode()*100+age; } } public class GsonTest { public static void main(String[] args) { Gson gson = new Gson(); System.out.println("1普通的Bean的转换**************************"); System.out.println("将一个Bean转换成为json字符串->"); User user1 = new User("凤姐",12,new StringBuffer("未知"),true); System.out.println("转换之前的user1"+user1); String json = gson.toJson(user1); System.out.println("User对象转换成为Json字符串,json==="+json); System.out.println("***************************"); System.out.println("将一个json字符串转换成为Bean->"); User user2 = gson.fromJson(json, User.class); System.out.println("转换成为的user2=="+user2); System.out.println(); System.out.println("2Collection集合的转换**************************"); System.out.println("将一个Bean的List集合转换成为json字符串->"); Collection<User> userList1 = new ArrayList<User>(); for(int i=0;i<3;i++){ User user = new User("如花",10+i,new StringBuffer("男"),false); userList1.add(user); } json = gson.toJson(userList1); System.out.println("User的List集合对象转换成为Json字符串,json==="+json); System.out.println("***************************"); System.out.println("将一个json字符串转换成为Bean的List集合->"); Collection<User> userList2 = gson.fromJson(json, new TypeToken<Collection<User>>(){}.getType()); System.out.println("转换成为的User的List集合,userList2="+userList2); System.out.println(); System.out.println("3Array数组的转换**************************"); System.out.println("将一个Bean的Array数组转换成为json字符串->"); User [] userArray1 = new User[3]; for(int i=0;i<userArray1.length;i++){ userArray1[i] = new User("芙蓉",20,new StringBuffer("人妖"),true); } json = gson.toJson(userArray1); System.out.println("User的数组对象转换成为Json字符串,json==="+json); System.out.println("***************************"); System.out.println("将一个json字符串转换成为Bean的数组对象->"); User [] userArray2 = gson.fromJson(json, new TypeToken<User[]>(){}.getType()); System.out.println("转换成为的User的数组对象,userArray2="+Arrays.toString(userArray2)); System.out.println(); System.out.println("4Map的转换**************************"); System.out.println("将一个Bean的Map转换成为json字符串->"); Map<String,User> map1 = new HashMap<String,User>(); for(int i=0;i<3;i++){ map1.put(""+(i+10), userArray1[i]); } json = gson.toJson(map1); System.out.println("User的Map集合转换成为Json字符串,json==="+json); System.out.println("***************************"); System.out.println("将一个json字符串转换成为Bean的数组对象->"); Map<String,User> map2 = gson.fromJson(json, new TypeToken<Map<String,User>>(){}.getType()); System.out.println("转换成为的User的数组对象,map2=="+map2); } }
Run results:
1普通的Bean的转换************************** 将一个Bean转换成为json字符串-> 转换之前的user1{name=凤姐;age=12;sex=未知;isChild=true} User对象转换成为Json字符串,json==={"name":"凤姐","age":12,"sex":"未知","isChild":true} *************************** 将一个json字符串转换成为Bean-> 转换成为的user2=={name=凤姐;age=12;sex=未知;isChild=true} 2Collection集合的转换************************** 将一个Bean的List集合转换成为json字符串-> User的List集合对象转换成为Json字符串,json===[{"name":"如花","age":10,"sex":"男","isChild":false},{"name":"如花","age":11,"sex":"男","isChild":false},{"name":"如花","age":12,"sex":"男","isChild":false}] *************************** 将一个json字符串转换成为Bean的List集合-> 转换成为的User的List集合,userList2=[{name=如花;age=10;sex=男;isChild=false}, {name=如花;age=11;sex=男;isChild=false}, {name=如花;age=12;sex=男;isChild=false}] 3Array数组的转换************************** 将一个Bean的Array数组转换成为json字符串-> User的数组对象转换成为Json字符串,json===[{"name":"芙蓉","age":20,"sex":"人妖","isChild":true},{"name":"芙蓉","age":20,"sex":"人妖","isChild":true},{"name":"芙蓉","age":20,"sex":"人妖","isChild":true}] *************************** 将一个json字符串转换成为Bean的数组对象-> 转换成为的User的数组对象,userArray2=[{name=芙蓉;age=20;sex=人妖;isChild=true}, {name=芙蓉;age=20;sex=人妖;isChild=true}, {name=芙蓉;age=20;sex=人妖;isChild=true}] 4Map的转换************************** 将一个Bean的Map转换成为json字符串-> User的Map集合转换成为Json字符串,json==={"10":{"name":"芙蓉","age":20,"sex":"人妖","isChild":true},"11":{"name":"芙蓉","age":20,"sex":"人妖","isChild":true},"12":{"name":"芙蓉","age":20,"sex":"人妖","isChild":true}} *************************** 将一个json字符串转换成为Bean的数组对象-> 转换成为的User的数组对象,map2=={10={name=芙蓉;age=20;sex=人妖;isChild=true}, 11={name=芙蓉;age=20;sex=人妖;isChild=true}, 12={name=芙蓉;age=20;sex=人妖;isChild=true}}
#For more GSON tutorials on implementing JSON serialization and deserialization of Java objects, please pay attention to the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software