Gson 是 Google 开发的Java API,是一个简单基于Java的开源库,可以相互转换Java对象和Json字符串
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
// 使用new方法
Gson gson = new Gson();
Gson gson = new GsonBuilder().create();
声明对象的时候可以加规则管控
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation() //序列化时排除没有@Expose注解的字段
.enableComplexMapKeySerialization() //当Map的key为复杂对象时,需要开启该方法
.serializeNulls() //字段值为空或null时,仍然进行转换
.setDateFormat("yyyy-MM-dd HH:mm:ss:SSS") //时间转化为Pattern的特定格式
.setPrettyPrinting() //对JSON美化
.disableHtmlEscaping() //防止特殊字符出现乱码
.create();
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.Data;
import org.junit.Test;
import java.util.*;
public class GsonTest {
//测试的实体类
@Data
public class TestEntity {
private String name;
private int age;
private String sex;
private Date birthday;
private String email;
private String address;
public TestEntity() {}
public TestEntity(String name, int age, String sex, Date birthday, String email, String address) {
this.name = name;
this.age = age;
this.sex = sex;
this.birthday = birthday;
this.email = email;
this.address = address;
}
}
@Test
public void gsonTset() {
//声明Gson对象
Gson gson = new Gson();
//声明Java对象,用于序列化
TestEntity entity = new TestEntity("盛夏 ",23,"未知",new Date(),"sx @xx.com",null);
TestEntity entity1 = new TestEntity("盛夏1",23,"未知",new Date(),"sx1@xx.com",null);
TestEntity entity2 = new TestEntity("盛夏2",23,"未知",new Date(),"sx2@xx.com",null);
//序列化方法 toJson || 反序列化方法 fromJson
/*-------序列化 对象 转化为 Json 字符串 -------*/
String objectToJson = gson.toJson(entity);
System.out.println(objectToJson);
//{"name":"盛夏","age":23,"sex":"未知","birthday":"Apr 26, 2022 11:20:09 AM","email":"sx@xx.com"}
/*-------反序列化 Json 转化为 Java 对象 -------*/
TestEntity jsonToObject = gson.fromJson(objectToJson, TestEntity.class);
System.out.println(jsonToObject);
//GsonTest.TestEntity(name=盛夏 , age=23, sex=未知, birthday=Tue Apr 26 11:34:06 CST 2022, email=sx @xx.com, address=null)
/*-------序列化 Map 转化为 Json 字符串 -------*/
Map map = new HashMap();
map.put("entity1",entity1);
map.put("entity2",entity2);
String mapToJson = gson.toJson(map);
System.out.println(mapToJson);
//{"entity1":{"name":"盛夏1","age":23,"sex":"未知","birthday":"Apr 26, 2022 11:28:49 AM","email":"sx1@xx.com"},
// "entity2":{"name":"盛夏2","age":23,"sex":"未知","birthday":"Apr 26, 2022 11:28:49 AM","email":"sx2@xx.com"}}
/*-------反序列化 Json 转化为 Map 集合 -------*/
Map jsonToMap = gson.fromJson(mapToJson, new TypeToken<Map<String, TestEntity>>() {}.getType());
System.out.println(jsonToMap);
//{entity1=GsonTest.TestEntity(name=盛夏1, age=23, sex=未知, birthday=Tue Apr 26 11:38:38 CST 2022, email=sx1@xx.com, address=null),
// entity2=GsonTest.TestEntity(name=盛夏2, age=23, sex=未知, birthday=Tue Apr 26 11:38:38 CST 2022, email=sx2@xx.com, address=null)}
/*-------序列化 List 转化为 Json 字符串 -------*/
List list = new ArrayList();
list.add(entity1);
list.add(entity2);
String listToJson = gson.toJson(list);
System.out.println(listToJson);
//[{"name":"盛夏1","age":23,"sex":"未知","birthday":"Apr 26, 2022 11:31:37 AM","email":"sx1@xx.com"},
// {"name":"盛夏2","age":23,"sex":"未知","birthday":"Apr 26, 2022 11:31:37 AM","email":"sx2@xx.com"}]
/*-------反序列化 Json 转化为 List 集合 -------*/
List jsonToList = gson.fromJson(listToJson, new TypeToken<List<TestEntity>>() {}.getType());
System.out.println(jsonToList);
// [GsonTest.TestEntity(name=盛夏1, age=23, sex=未知, birthday=Tue Apr 26 11:41:01 CST 2022, email=sx1@xx.com, address=null),
// GsonTest.TestEntity(name=盛夏2, age=23, sex=未知, birthday=Tue Apr 26 11:41:01 CST 2022, email=sx2@xx.com, address=null)]
}
}
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import lombok.Data;
import org.junit.Test;
import java.util.*;
public class GsonTest {
//测试的实体类
@Data
public class TestEntity {
/*---注解SerializedName使用---*/
// value = "userName" 给实体类字段取别名 ; name --> userName
// alternate = {"alterName","uName"} 可用于反序列化,{"alterName","uName"}都可给name赋值
@SerializedName(value = "userName",alternate = {"alterName","uName"})
private String name;
private int age;
private String sex;
private Date birthday;
private String email;
private String address;
public TestEntity() {}
public TestEntity(String name, int age, String sex, Date birthday, String email, String address) {
this.name = name;
this.age = age;
this.sex = sex;
this.birthday = birthday;
this.email = email;
this.address = address;
}
}
@Test
public void gsonTset() {
//声明Gson对象
Gson gson = new Gson();
//声明Java对象,用于序列化
TestEntity entity = new TestEntity("盛夏 ",23,"未知",new Date(),"sx @xx.com",null);
// name 序列化为 userName
String toJson = gson.toJson(entity);
System.out.println(toJson);
//{"userName":"盛夏 ","age":23,"sex":"未知","birthday":"Apr 27, 2022 5:15:57 PM","email":"sx @xx.com"}
// 用 name 反序列化来给 name 赋值 ;会出现赋值不上
String nameJsonToObject = "{\"name\":\"盛夏 \",\"age\":23,\"sex\":\"未知\",\"birthday\":\"Apr 27, 2022 5:15:57 PM\",\"email\":\"sx @xx.com\"}";
TestEntity entity1 = gson.fromJson(nameJsonToObject, TestEntity.class);
System.out.println(entity1);
//GsonTest.TestEntity(name=null, age=23, sex=未知, birthday=Wed Apr 27 17:15:57 CST 2022, email=sx @xx.com, address=null)
// 用 alterName 反序列化来给 name 赋值 ,可赋值成功
String alterNameJsonToObject = "{\"alterName\":\"盛夏 \",\"age\":23,\"sex\":\"未知\",\"birthday\":\"Apr 27, 2022 5:15:57 PM\",\"email\":\"sx @xx.com\"}";
TestEntity entity2 = gson.fromJson(alterNameJsonToObject, TestEntity.class);
System.out.println(entity2);
//GsonTest.TestEntity(name=盛夏 , age=23, sex=未知, birthday=Wed Apr 27 17:15:57 CST 2022, email=sx @xx.com, address=null)
// 用 uName 反序列化来给 name 赋值 ,可赋值成功
String uNameJsonToObject = "{\"uName\":\"盛夏 \",\"age\":23,\"sex\":\"未知\",\"birthday\":\"Apr 27, 2022 5:15:57 PM\",\"email\":\"sx @xx.com\"}";
TestEntity entity3 = gson.fromJson(uNameJsonToObject, TestEntity.class);
System.out.println(entity3);
//GsonTest.TestEntity(name=盛夏 , age=23, sex=未知, birthday=Wed Apr 27 17:15:57 CST 2022, email=sx @xx.com, address=null)
// 用 userName 反序列化来给 name 赋值 ,可赋值成功
String newJsonToObject = toJson ;
TestEntity entity4 = gson.fromJson(newJsonToObject, TestEntity.class);
System.out.println(entity4);
//GsonTest.TestEntity(name=盛夏 , age=23, sex=未知, birthday=Wed Apr 27 17:20:11 CST 2022, email=sx @xx.com, address=null)
}
}
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import lombok.Data;
import org.apache.poi.ss.formula.functions.T;
import org.junit.Test;
import java.util.*;
public class GsonTest {
//测试的实体类
@Data
public class TestEntity {
/*---Expose ---*/
// @Expose(serialize=true) : 序列化的时候是否 序列化该字段 【true:序列化 ;false:不序列化】
// @Expose(deserialize=true) : 反序列化的时候是否 反序列化该字段 【true:反序列化 ;false:不反序列化】
@Expose(serialize = true)
private String name;
@Expose(deserialize = true)
private int age;
@Expose(serialize = false)
private String sex;
@Expose(deserialize = false)
private Date birthday;
private String email;
private String address;
public TestEntity() {}
public TestEntity(String name, int age, String sex, Date birthday, String email, String address) {
this.name = name;
this.age = age;
this.sex = sex;
this.birthday = birthday;
this.email = email;
this.address = address;
}
}
@Test
public void gsonTset() {
//声明Gson对象
Gson gson = new Gson();
//声明Gson对象
// 不加 @Expose 注解 等于 @Expose(serialize = false , deserialize = false)
Gson buildGson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
//声明Java对象,用于序列化
TestEntity entity = new TestEntity("盛夏 ",23,"未知",new Date(),"sx @xx.com",null);
// 用 gson 序列化 会毫无反映
String objectToJson = gson.toJson(entity);
System.out.println(objectToJson);
// {"name":"盛夏 ","age":23,"sex":"未知","birthday":"Apr 27, 2022 5:42:21 PM","email":"sx @xx.com"}
// 用 buildGson 序列化
String objectToBuildJson = buildGson.toJson(entity);
// name 字段会被序列化 ;sex 字段不会被序列化
System.out.println(objectToBuildJson);
//{"name":"盛夏 ","age":23,"birthday":"Apr 27, 2022 5:47:20 PM"}
// 用 buildGson 反序列化
TestEntity buildEntity = buildGson.fromJson(objectToBuildJson, TestEntity.class);
// age字段 会被反序列化 ; birthday字段 不会被序列化
System.out.println(buildEntity);
//GsonTest.TestEntity(name=盛夏 , age=23, sex=null, birthday=null, email=null, address=null)
}
}
不怎么用
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.nisco.common.core.util.DateUtil;
import lombok.Data;
import lombok.SneakyThrows;
import org.apache.poi.ss.formula.functions.T;
import org.junit.Test;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class GsonTest {
//测试的实体类
@Data
public class TestEntity {
private String name;
private int age;
private String sex;
// 这注解不咋会用 参数是个类 这个类要继承TypeAdapter,重写read和write方法,用于序列化和反序列化
@JsonAdapter(FormatDate.class)
private Date birthday;
private String email;
private String address;
public TestEntity() {}
public TestEntity(String name, int age, String sex, Date birthday, String email, String address) {
this.name = name;
this.age = age;
this.sex = sex;
this.birthday = birthday;
this.email = email;
this.address = address;
}
}
@Test
public void gsonTset() {
//声明Gson对象
Gson gson = new Gson();
//声明Java对象,用于序列化
TestEntity entity = new TestEntity("盛夏 ",23,"未知",new Date(),"sx @xx.com",null);
String objectToJson = gson.toJson(entity);
System.out.println(objectToJson);
//{"name":"盛夏 ","age":23,"sex":"未知","birthday":2022-04-27-18-25-16,"email":"sx @xx.com"}
TestEntity entity1 = gson.fromJson(objectToJson, entity.getClass());
System.out.println(entity1);
//GsonTest.TestEntity(name=盛夏 , age=23, sex=未知, birthday=Wed Apr 27 18:25:16 CST 2022, email=sx @xx.com, address=null)
}
class FormatDate extends TypeAdapter {
public static final String DATE_FORMAT_DASH_TIME = "yyyy-MM-dd-HH-mm-ss"; // 对格式化有要求,不太会用
public FormatDate(){ }
@Override
public void write(JsonWriter out, Object value) throws IOException {
if (value == null) {
out.nullValue();
} else {
out.jsonValue(new SimpleDateFormat(DATE_FORMAT_DASH_TIME).format(value));
}
}
@SneakyThrows
@Override
public Object read(JsonReader in) throws IOException {
return new SimpleDateFormat(DATE_FORMAT_DASH_TIME,Locale.CHINA).parse(in.nextString());
}
}
}
另外:可以直接用这个进行日期格式化
Gson gson = new GsonBuilder().setDateFormat("yyyyMMdd").create();