淺談Java中FastJson的使用
FastJson的使用
使用maven導(dǎo)入依賴包
<!--下邊依賴跟aop沒關(guān)系,只是項(xiàng)目中用到了 JSONObject,所以引入fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
常用方法:
1.JSON.toJSONString(obejct) - java對(duì)象轉(zhuǎn)JSON字符串,
注意:
默認(rèn)情況下,如果int類型和boolean類型的屬性沒賦值的時(shí)候 (public boolean a; public int b;),調(diào)用 JSON.toJSONString(obejct) 序列化后,a和b不會(huì)被過濾掉,而是返回boolean類型和int類型的默認(rèn)值 false和0。當(dāng)然其他類型如果沒有賦值,序列化時(shí),會(huì)被過濾掉。
來看下例子就明白了
public class Test {
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
User user = new User();
user.setName("123");
userList.add(user);
System.out.println(JSON.toJSONString(userList));
}
public static class User{
private String name;
private int age;
public boolean health;
public Date time;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
先給name賦值,其他的都不賦值,結(jié)果time屬性被過濾掉了,如下:

再看下都不賦值的情況,結(jié)果name和time屬性都被過濾掉了,而int類型的age和boolean類型的health屬性取得時(shí)類型的默認(rèn)值:

2.JSON.parseObject(string, User.class) - JSON字符串轉(zhuǎn)java對(duì)象
(1)List集合轉(zhuǎn)JSON
@RestController
public class Json {
@RequestMapping(value = "/json")
public String json() throws Exception{
List<User> userList = new ArrayList<>();
userList.add(new User("1", "1", 20));
String res = JSON.toJSONString(userList);
return res;
}
}

(2)Map集合轉(zhuǎn)JSON
package com.lxc.Test;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Json {
public static void main(String[] args) {
Map<String, Object> userList = new HashMap<>();
for(int i = 0; i < 5; i ++) {
userList.put("user"+i, new User("name"+i, 20+i));
}
System.out.println("json:"+JSON.toJSONString(userList));
}
public static class User{
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}

反序列化
1.JSON轉(zhuǎn)Java對(duì)象 - JSON.perseObject()
public class Json {
public static void main(String[] args) {
String json = "{\"age\":20,\"name\":\"name0\"}";
System.out.println(JSON.parseObject(json, User.class)+"");
}
}
![]()
2.JSON轉(zhuǎn)Java集合 - JSON.perseArray()
public class Json {
public static void main(String[] args) {
String json = "[{\"age\":20,\"name\":\"name0\"}]";
List<User> userList = JSON.parseArray(json, User.class);
userList.forEach(System.out::println);
}
}
![]()
JSON.toJSONString() 參數(shù) - SerializerFeature枚舉常量
toJSONString 靜態(tài)方法參數(shù)有兩個(gè):
參數(shù)一:要序列化的對(duì)象;
參數(shù)二:SerializerFeature 枚舉類型的可變參數(shù) ( 我們可以傳遞多個(gè)參數(shù) ),進(jìn)行序列化時(shí),我們可以定義特殊的需求。

1.SerializerFeature.WriteMapNullValue
對(duì)一個(gè)對(duì)象或者列表進(jìn)行序列化時(shí),默認(rèn)情況下如果屬性值為null,序列化后的結(jié)果會(huì)過濾掉其屬性,如果想保留其屬性值,可以使用 SerializerFeature.WriteMapNullValue。
public class Json {
public static void main(String[] args) {
User user = new User();
user.setAge(20);
String res = JSON.toJSONString(user, SerializerFeature.WriteMapNullValue);
System.out.println(res);
}
public static class User{
private String name = null;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
}
2.SerializerFeature.WriteNullStringAsEmpty
對(duì)一個(gè)對(duì)象或者列表進(jìn)行序列,把屬性值為null的字段進(jìn)行轉(zhuǎn)化為 "" 雙引號(hào)。
public class Json {
public static void main(String[] args) {
User user = new User();
user.setAge(20);
String res = JSON.toJSONString(user, SerializerFeature.WriteNullStringAsEmpty);
System.out.println(res);
}
}
![]()
3.SerializerFeature.WriteNullNumberAsZero
序列之后, 把屬性值為 null 的屬性轉(zhuǎn)化為 0,這個(gè)前提是此屬性是 int 類型的!
public class Json {
public static void main(String[] args) {
User user = new User();
user.setName("測試");
String res = JSON.toJSONString(user, SerializerFeature.WriteNullNumberAsZero);
System.out.println(res);
}
}
![]()
4.SerializerFeature.WriteNullBooleanAsFalse
序列之后, 把屬性值為 null 的屬性轉(zhuǎn)化為 false,這個(gè)前提是此屬性是 boolean 類型的!
@Data
public class User{
private String name;
private int age;
private boolean health;
}

5.SerializerFeature.WriteDateUseDateFormat
把時(shí)間戳序列化為正常的時(shí)間,默認(rèn)輸出JSON.toJSONString() 序列之后, 默認(rèn)輸出如下:
![]()
添加 SerializerFeature.WriteDateUseDateFormat 之后的效果:

@Data
public class User{
private String name;
private int age;
private Date birthday = new Date();
private boolean health;
}
6.SerializerFeature.PrettyFormat
序列化的數(shù)據(jù)縱向布局。

@JSonField() 注解
在序列化時(shí),進(jìn)行個(gè)性定制!該注解的作用于方法上,字段上、參數(shù)上,可在序列化和反序列化時(shí)進(jìn)行特性功能定制。

1.注解屬性 name序列化后的名字(單獨(dú)序列化,對(duì)屬性名進(jìn)行修改)
@JSONField(name="username") private String name;
![]()
2.注解屬性 ordinal序列化后的順序(字段的排序)
@JSONField(ordinal = 1) private String name; @JSONField(ordinal = 2) private int age;

3.注解屬性 format 序列化后的格式
@JSONField(format = "YYYY-MM-dd") private Date birthday = new Date();
![]()
4.注解屬性 serialize 是否序列化該字段(默認(rèn)為true,如果false,當(dāng)字段值為null時(shí),會(huì)被過濾掉)
5.使用serializeUsing來定制屬性的序列化類
![]()
什么意思呢,類似vue中的過濾器,可以單獨(dú)訂制處理類下的某個(gè)屬性:
第一步:編寫一個(gè)類A,實(shí)現(xiàn)ObjectSerializer 接口;
第二步:重寫write方法;
第三步:在需要定制化的屬性上邊 添加注解,@JSONField(serializeUsing = A.class)
具體實(shí)現(xiàn)如下:
public class Json {
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
User user = new User();
user.setName("測試,");
userList.add(user);
System.out.println(JSON.toJSONString(userList));
}
public static class SerializeUsingFn implements ObjectSerializer {
@Override
public void write(JSONSerializer jsonSerializer, Object fieldValue, Object fieldName, Type fieldType, int i) throws IOException {
System.out.println(fieldValue); // 測試,
System.out.println(fieldName); // name
System.out.println(fieldType); // String
System.out.println(i); // 0
String name = (String) fieldValue; // 向下轉(zhuǎn)型,獲取到age屬性值
String filterName = name + "呵呵"; // 這里可以對(duì)name屬性進(jìn)行定制化
jsonSerializer.write(filterName); // 調(diào)用write方法
}
}
public static class User{
@JSONField(serializeUsing = SerializeUsingFn.class)
private String name;
private int age;
public boolean health;
public Date time;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
可以看到name字段值 被修改了后邊添加了 "呵呵" 倆字。

@JSONType() 注解
只能作用在類上,也是對(duì)類里邊的字段進(jìn)行序列化

@JSONType()注解中的屬性
· includes 要序列化的字段(注意:如果字段上有 @serialize(true),如果沒有includes字段也不會(huì)被序列化),它是一個(gè)數(shù)組,源碼如下:

@Data
@JSONType(includes = {"name", "age"})
public class User{
private String name;
private int age;
private boolean health;
private Date birthday = new Date();
}

· orders序列化后的字段順序,也是一個(gè)數(shù)組,源碼如下:
![]()
@JSONType(includes = {"name","birthday", "health", "age"}, orders = {"age","name","birthday","health"})
public static class User{
private String name;
private int age;
private boolean health;
private Date birthday = new Date();
}

FastJson屬性名過濾器
過濾字段,通過 SimplePropertyPreFilter 過濾器,來過濾指定的屬性名,然后在轉(zhuǎn)JSON的時(shí)候,帶上過濾器參數(shù)即可。
例如,把下邊屬性health 過濾掉:
// userList = [{"age":20,"health":true,"name":"測試,呵呵","time":"2021-06-29 09:40:55"}]
SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
// 下邊方法也很好理解:調(diào)用過濾器上邊的getExcludes排除字段的方法,什么字段需要排除呢:add() 添加需要排除的字段即可
filter.getExcludes().add("health");
System.out.println(JSON.toJSONString(userList, filter));
![]()
當(dāng)然,如果需要排除大量的字段,保留一個(gè)字段,可以使用:filter.getIncludes() .add("xxx") 方法,意思:只保留xxx屬性,其他的都會(huì)被過濾。
如果過濾或者添加多個(gè)字段,可以使用:addAll() 方法,參數(shù)必須是一個(gè)集合Collection 。
![]()
過濾多個(gè)字段:
SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
List<String> r = new ArrayList<>() {
{
add("health");
add("name");
}
};
filter.getExcludes().addAll(r);
System.out.println(JSON.toJSONString(userList, filter));

暫時(shí)就這么多,項(xiàng)目中用到別的方法在記錄!
到此這篇關(guān)于淺談Java中FastJson的使用的文章就介紹到這了,更多相關(guān)FastJson的使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一文詳解Spring事務(wù)的實(shí)現(xiàn)與本質(zhì)
這篇文章主要介紹了Spring中事務(wù)的兩種實(shí)現(xiàn)方式:聲明式事務(wù)、編程式事務(wù)以及他們的本質(zhì)。文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-04-04
Java Set接口及常用實(shí)現(xiàn)類總結(jié)
Collection的另一個(gè)子接口就是Set,他并沒有我們List常用,并且自身也沒有一些額外的方法,全是繼承自Collection中的,因此我們還是簡單總結(jié)一下,包括他的常用實(shí)現(xiàn)類HashSet、LinkedHashSet、TreeSet的總結(jié)2023-01-01
自定義log4j2中的Appender來獲取日志內(nèi)容的示例代碼
在 Log4j2 中,Appender 是負(fù)責(zé)將日志事件輸出到目標(biāo)地點(diǎn)的組件,本文講述的是通過 log4j 中自定義的 Appender 來獲取需要打印的日志信息,文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下2024-02-02
SpringCloud持久層框架MyBatis Plus的使用與原理解析
MyBatisPlus為MyBatis的增強(qiáng)版,專注于簡化數(shù)據(jù)庫操作,提供自動(dòng)化CRUD、內(nèi)置分頁和樂觀鎖等功能,極大提升開發(fā)效率,在SpringCloud微服務(wù)架構(gòu)中,MyBatisPlus通過插件機(jī)制和自動(dòng)生成代碼功能,有效支持企業(yè)級(jí)應(yīng)用和分布式系統(tǒng)的開發(fā)2024-10-10
spring boot mybatis多數(shù)據(jù)源解決方案過程解析
這篇文章主要介紹了spring boot mybatis多數(shù)據(jù)源解決方案過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11

