1. fastjson使用
1.1 參考鏈接
https://www.cnblogs.com/jajian/p/10051901.html
1.2 下載地址
https://mvnrepository.com/artifact/com.alibaba/fastjson
1.3 基本用法
String toJSONString(Object object)
- 把java任意類型對象轉換爲json字符串(序列化)
<T> T parseObject(String text, Class<T> clazz)
- 把 json字符串轉化爲java對象(反序列化)
<T> T parseObject(String text, TypeReference<T> type)
- 把json字符串反序列化爲泛型類
Book book1=new Book(1,"西遊記",new Date());
Book book2=new Book(2,"紅樓夢",new Date());
List<Book> bookList=new ArrayList<Book>();
bookList.add(book1);
bookList.add(book2);
//1.JSON.toJSONString可把各種類型的java數據轉換爲json字符串
String json_book=JSON.toJSONString(book1);
String json_list=JSON.toJSONString(bookList);
//2.把json字符串轉換爲java對象
Book book_object=JSON.parseObject(json_book,Book.class);
//3.把json字符串轉換爲泛型對象集合(注意別漏了大括號)
List<Book> bookList_object=JSON.parseObject(json_list,new TypeReference<List<Book>>(){});
//錯誤示例,運行時會報錯,反序列化爲泛型類時,必須用TypeReference
//List<Book> bookList_object=JSON.parseObject(json_list,List.class);
1.4 SerializerFeature枚舉
1.3基本用法
的方法後面的參數都可以加上這個SerializerFeature枚舉- 例子參考
1.5日期轉換
1.5 設置日期轉換格式
- 1.5.1 序列化日期
-
String toJSONStringWithDateFormat(Object object, String dateFormat)
- 序列化時自定義日期轉換格式
-
String toJSONString(object,SerializerFeature.WriteDateUseDateFormat)
- 序列化時使用默認的日期轉換格式,
JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"
,這個全局的日期轉換格式不建議修改
- 序列化時使用默認的日期轉換格式,
-
//不使用日期轉換格式:1589970177824
String json_book1=JSON.toJSONString(book);
//使用自定義的日期轉換格式(yyyy-MM-dd):2020-05-20
String json_book2=JSON.toJSONStringWithDateFormat(book,"yyyy-MM-dd");
//使用默認的日期轉換格式(yyyy-MM-dd HH:mm:ss):2020-05-20 18:22:57
String json_book3=JSON.toJSONString(book,SerializerFeature.WriteDateUseDateFormat);
- 1.5.2 反序列化日期
- 反序列化時會自動使用多種日期格式進行轉換爲Date類型,不用額外的設置
//反序列化時自動會對日期字符串或毫秒數進行多種格式轉換
String json1="{'book_name':'西遊記','id':1,'publishDate':'2012/12/1 12:25:11'}";
Book book1=JSON.parseObject(json1, Book.class);
String json2="{'book_name':'西遊記','id':1,'publishDate':1589972261259}";
Book book2=JSON.parseObject(json2, Book.class);
1.6 篩選屬性
-
使用SimplePropertyPreFilter類對屬性進行篩選
Book book=new Book(1,"西遊記",new Date());
//1.排除屬性SimplePropertyPreFilter.excludes
//{"book_name":"西遊記"}
SimplePropertyPreFilter excludeFilter = new SimplePropertyPreFilter();
excludeFilter.getExcludes().add("id");
excludeFilter.getExcludes().add("publishDate");
String json1=JSON.toJSONString(book,excludeFilter);
//2.保留屬性SimplePropertyPreFilter.includes
//{"book_name":"西遊記","id":1}
SimplePropertyPreFilter includeFilter = new SimplePropertyPreFilter();
includeFilter.getIncludes().add("id");
includeFilter.getIncludes().add("book_name");
String json2=JSON.toJSONString(book,includeFilter);
//3.作用跟2一樣,使用了構造方法設置了保留屬性
//{"book_name":"西遊記","id":1}
String json3=JSON.toJSONString(book,new SimplePropertyPreFilter("id","book_name"));
1.7 定製序列化
- 參考第1.1點的鏈接
2. fastjson自定義工具類FastjsonUtil
2.1 方法說明
- 方法名中包含了
DateFormat
表示該方法包含了日期轉換的功能,方法參數dateFormat
表示自定義的日期轉換格式,參數值爲null或空字符串是會使用默認值yyyy-MM-dd HH:mm:ss
- 方法名包含了
Excludes
表示該方法包含了序列化時排除
屬性的功能,方法參數excludes
表示排除
的屬性,多個屬性用逗號,隔開 - 方法名包含了
Includes
表示該方法包含了序列化時包含
屬性的功能,方法參數includes
表示包含
的屬性,多個屬性用逗號,隔開 - 方法名開頭是
writeJSON
表示序列化對象返回json字符串並響應輸出到客戶端,輸出前已設置了響應頭text/json;charset=utf-8
,所以中文不會亂碼,而且客戶端js可以直接使用json對象,不用再類型轉換或聲明json - 大部分方法最後的方法參數是可變參數
SerializerFeature
,用得不多,所以後面不再舉例說明,想深入瞭解請看1.4 - 方法
parseObject
跟JSON類的方法是一模一樣的
package com.utils;
import java.io.IOException;
import javax.servlet.ServletResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
/***
*
* @author duson
* @date 2020-5-21
* @version 1.1
*
*/
public class FastjsonUtil {
public final static String DATEFORMAT="yyyy-MM-dd"; //只包含年月日的轉換格式
public final static String TIMEFORMAT="HH:mm:ss"; //只包含時分秒的轉換格式
public final static String DATETIMEFORMAT="yyyy-MM-dd HH:mm:ss"; //包含了年月日時分秒的轉換格式
private final static String DEFAULTFORMAT=DATETIMEFORMAT; //默認日期轉換格式
/**
* 把json字符串以json格式寫出到客戶端
* @param response 響應對象
* @param json json字符串
* @throws IOException
*/
public static void writeJSON(ServletResponse response,String json) throws IOException{
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(json);
}
/**
* 根據排除屬性字符串創建屬性過濾器
* @param excludes 需要排除的屬性,多個屬性用逗號,隔開
* @return 設置了排除屬性的過濾器
*/
public static SimplePropertyPreFilter getExcludeFilter(String excludes){
SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
String[] arr=excludes.split(",");
for (String ex : arr) {
filter.getExcludes().add(ex);
}
return filter;
}
/**
* 根據包含屬性字符串創建屬性過濾器
* @param includes 需要包含的屬性,多個屬性用逗號,隔開
* @return 設置了包含屬性的過濾器
*/
public static SimplePropertyPreFilter getIncludeFilter(String includes){
SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
String[] arr=includes.split(",");
for (String ex : arr) {
filter.getIncludes().add(ex);
}
return filter;
}
/**
* 日期轉換格式null值或空字符串會使用默認的日期轉換格式
* @param dateFormat
* @return
*/
private static String getDateFormat(String dateFormat){
if(dateFormat==null||dateFormat.trim().isEmpty()){
return DEFAULTFORMAT;
}else{
return dateFormat;
}
}
/**
* 把對象序列化爲JSON字符串
* @param object java對象
* @param features SerializerFeature枚舉
* @throws IOException
*/
public static String toJSONString(Object object,SerializerFeature... features) {
return JSON.toJSONString(object, features);
}
/**
* 把對象序列化爲JSON字符串並寫出到客戶端
* @param response 響應對象
* @param object java對象
* @param features SerializerFeature枚舉
* @throws IOException
*/
public static void writeJSON(ServletResponse response,Object object,SerializerFeature... features) throws IOException{
writeJSON(response, toJSONString(object, features));
}
/**
* 把對象序列化爲JSON字符串,可以指定需要排除的屬性
* @param object java對象
* @param excludes 需要排除的屬性,多個屬性用逗號,隔開
* @param features SerializerFeature枚舉
* @return
*/
public static String toJSONStringWithExcludes(Object object, String excludes,SerializerFeature... features) {
return JSON.toJSONString(object, getExcludeFilter(excludes),features);
}
/**
* 把對象序列化爲JSON字符串並寫出到客戶端,可以指定需要排除的屬性
* @param response 響應對象
* @param object java對象
* @param excludes 需要排除的屬性,多個屬性用逗號,隔開
* @param features SerializerFeature枚舉
* @return
* @throws IOException
*/
public static void writeJSONWithExcludes(ServletResponse response,Object object, String excludes,SerializerFeature... features) throws IOException {
writeJSON(response,toJSONStringWithExcludes(object, excludes, features));
}
/**
* 把對象序列化爲JSON字符串,可以指定需要包含的屬性
* @param object java對象
* @param includes 需要包含的屬性,多個屬性用逗號,隔開
* @param features SerializerFeature枚舉
* @return
*/
public static String toJSONStringWithIncludes(Object object, String includes,SerializerFeature... features) {
return JSON.toJSONString(object, getIncludeFilter(includes),features);
}
/**
* 把對象序列化爲JSON字符串並寫出到客戶端,可以指定需要包含的屬性
* @param response 響應對象
* @param object java對象
* @param includes 需要包含的屬性,多個屬性用逗號,隔開
* @param features SerializerFeature枚舉
* @return
* @throws IOException
*/
public static void writeJSONWithIncludes(ServletResponse response,Object object, String includes,SerializerFeature... features) throws IOException {
writeJSON(response,toJSONStringWithIncludes(object, includes,features));
}
/**
*
* 把對象序列化爲JSON字符串,可以指定日期轉換格式
* @param object java對象
* @param dateFormat 日期轉換格式,如果值爲null或空字符串會使用默認的日期轉換格式
* @param features SerializerFeature枚舉
* @return
*/
public static String toJSONStringWithDateFormat(Object object, String dateFormat,SerializerFeature... features) {
return JSON.toJSONStringWithDateFormat(object, getDateFormat(dateFormat), features);
}
/**
*
* 把對象序列化爲JSON字符串並寫出到客戶端,可以指定日期轉換格式
* @param response 響應對象
* @param object java對象
* @param dateFormat 日期轉換格式,如果值爲null或空字符串會使用默認的日期轉換格式
* @param features SerializerFeature枚舉
* @return
* @throws IOException
*/
public static void writeJSONWithDateFormat(ServletResponse response,Object object, String dateFormat,SerializerFeature... features) throws IOException {
writeJSON(response, toJSONStringWithDateFormat(object, dateFormat, features));
}
/**
*
* 把對象序列化爲JSON字符串,使用默認的日期轉換格式
* @param response 響應對象
* @param object java對象
* @param features SerializerFeature枚舉
* @return
*/
public static String toJSONStringWithDefaultDateFormat(Object object,SerializerFeature... features) {
return toJSONStringWithDateFormat(object,DEFAULTFORMAT, features);
}
/**
*
* 把對象序列化爲JSON字符串並寫出到客戶端,使用默認的日期轉換格式
* @param object java對象
* @param features SerializerFeature枚舉
* @return
* @throws IOException
*/
public static void writeJSONWithDefaultDateFormat(ServletResponse response,Object object,SerializerFeature... features) throws IOException {
writeJSON(response, toJSONStringWithDefaultDateFormat(object, features));
}
/**
*
* 把對象序列化爲JSON字符串,可以指定日期轉換格式,可以指定排除的屬性
* @param object java對象
* @param dateFormat 日期轉換格式,如果值爲null或空字符串會使用默認的日期轉換格式
* @param excludes 需要排除的屬性,多個屬性用逗號,隔開
* @param features SerializerFeature枚舉
* @return
*/
public static String toJSONStringWithDateFormatAndExcludes(Object object, String dateFormat, String excludes,SerializerFeature... features) {
return JSON.toJSONString(object, SerializeConfig.globalInstance, new SerializeFilter[]{getExcludeFilter(excludes)}, getDateFormat(dateFormat), JSON.DEFAULT_GENERATE_FEATURE, features);
}
/**
*
* 把對象序列化爲JSON字符串並寫出到客戶端,可以指定日期轉換格式,可以指定排除的屬性
* @param response 響應對象
* @param object java對象
* @param dateFormat 日期轉換格式,如果值爲null或空字符串會使用默認的日期轉換格式
* @param excludes 需要排除的屬性,多個屬性用逗號,隔開
* @param features SerializerFeature枚舉
* @return
* @throws IOException
*/
public static void writeJSONWithDateFormatAndExcludes(ServletResponse response,Object object, String dateFormat, String excludes,SerializerFeature... features) throws IOException {
writeJSON(response, toJSONStringWithDateFormatAndExcludes(object, dateFormat, excludes, features));
}
/**
*
* 把對象序列化爲JSON字符串,可以指定日期轉換格式,可以指定包含的屬性
* @param object java對象
* @param dateFormat 日期轉換格式,如果值爲null或空字符串會使用默認的日期轉換格式
* @param includes 需要包含的屬性,多個屬性用逗號,隔開
* @param features SerializerFeature枚舉
* @return
*/
public static String toJSONStringWithDateFormatAndIncludes(Object object, String dateFormat, String includes,SerializerFeature... features) {
return JSON.toJSONString(object, SerializeConfig.globalInstance, new SerializeFilter[]{getIncludeFilter(includes)}, getDateFormat(dateFormat), JSON.DEFAULT_GENERATE_FEATURE, features);
}
/**
*
* 把對象序列化爲JSON字符串並寫出到客戶端,,可以指定日期轉換格式,可以指定包含的屬性
* @param response 響應對象
* @param object java對象
* @param dateFormat 日期轉換格式,如果值爲null或空字符串會使用默認的日期轉換格式
* @param includes 需要包含的屬性,多個屬性用逗號,隔開
* @param features SerializerFeature枚舉
* @return
* @throws IOException
*/
public static void writeJSONWithDateFormatAndIncludes(ServletResponse response,Object object, String dateFormat, String includes,SerializerFeature... features) throws IOException {
writeJSON(response, toJSONStringWithDateFormatAndIncludes(object, dateFormat, includes, features));
}
/**
* 把json字符串轉換爲java類對象
* @param jsonString json字符串
* @param clazz java類.class
* @return
*/
public static <T> T parseObject(String jsonString, Class<T> clazz){
return JSON.parseObject(jsonString, clazz);
}
/**
* 把json字符串轉換爲java泛型類對象
* @param jsonString json字符串
* @param type 泛型類型, 舉例:泛型類返回值List<Book>,參數要填寫 new TypeReference<List<Book>>(){}
* @return
*/
public static <T> T parseObject(String jsonString,TypeReference<T> type){
return JSON.parseObject(jsonString,type);
}
}
2.2 方法使用
- java對象轉換爲json字符串
toJSONStringxxxxxxxxxxxx()
Book book=new Book(1,"西遊記",new Date());
//基本用法
//{"book_name":"西遊記","id":1,"publishDate":1590029520053}
String json1=FastjsonUtil.toJSONString(book);
//設置日期轉換格式,null值或空字符串都會使用默認的日期轉換格式
//json2~6結果都是一樣的
//{"book_name":"西遊記","id":1,"publishDate":"2020-05-21 10:52:00"}
String json2=FastjsonUtil.toJSONStringWithDefaultDateFormat(book);
String json3=FastjsonUtil.toJSONStringWithDateFormat(book,null);
String json4=FastjsonUtil.toJSONStringWithDateFormat(book,"");
String json5=FastjsonUtil.toJSONStringWithDateFormat(book,FastjsonUtil.DATETIMEFORMAT);
String json6=FastjsonUtil.toJSONStringWithDateFormat(book, "yyyy-MM-dd HH:mm:ss");
//設置序列化排除的屬性
//{"book_name":"西遊記"}
String json7=FastjsonUtil.toJSONStringWithExcludes(book, "id,publishDate");
//設置序列化包含的屬性
//{"book_name":"西遊記","id":1}
String json8=FastjsonUtil.toJSONStringWithIncludes(book, "id,book_name");
//同時設置日期轉換格式和序列化排除的屬性
//{"book_name":"西遊記","publishDate":"10:52:00"}
String json9=FastjsonUtil.toJSONStringWithDateFormatAndExcludes(book, FastjsonUtil.TIMEFORMAT, "id");
//同時設置日期轉換格式和序列化包含的屬性
//{"id":1,"publishDate":"2020-05-21 10:52:00"}
String json10=FastjsonUtil.toJSONStringWithDateFormatAndIncludes(book, null, "id,publishDate");
- java對象轉換爲json字符串並響應輸出到客戶端
writeJSONxxxxxxxxxx()
Book book=new Book(1,"西遊記",new Date());
//把序列化後的json字符串響應輸出到客戶端
//{"book_name":"西遊記","id":1,"publishDate":1590029520053}
FastjsonUtil.writeJSON(ServletActionContext.getResponse(), book);
//設置日期轉換格式並響應輸出到客戶端,null值或空字符串都會使用默認的日期轉換格式
//下面5條結果都是一樣的
//{"book_name":"西遊記","id":1,"publishDate":"2020-05-21 10:52:00"}
FastjsonUtil.writeJSONWithDefaultDateFormat(ServletActionContext.getResponse() ,book);
FastjsonUtil.writeJSONWithDateFormat(ServletActionContext.getResponse(), book,null);
FastjsonUtil.writeJSONWithDateFormat(ServletActionContext.getResponse(), book,"");
FastjsonUtil.writeJSONWithDateFormat(ServletActionContext.getResponse(), book,FastjsonUtil.DATETIMEFORMAT);
FastjsonUtil.writeJSONWithDateFormat(ServletActionContext.getResponse(), book, "yyyy-MM-dd HH:mm:ss");
//設置序列化排除的屬性並響應輸出到客戶端
//{"book_name":"西遊記"}
FastjsonUtil.writeJSONWithExcludes(ServletActionContext.getResponse(),book, "id,publishDate");
//設置序列化包含的屬性並響應輸出到客戶端
//{"book_name":"西遊記","id":1}
FastjsonUtil.writeJSONWithIncludes(ServletActionContext.getResponse(),book, "id,book_name");
//同時設置日期轉換格式和序列化排除的屬性並響應輸出到客戶端
//{"book_name":"西遊記","publishDate":"10:52:00"}
FastjsonUtil.writeJSONWithDateFormatAndExcludes(ServletActionContext.getResponse(),book, FastjsonUtil.TIMEFORMAT, "id");
//同時設置日期轉換格式和序列化包含的屬性並響應輸出到客戶端
//{"id":1,"publishDate":"2020-05-21 10:52:00"}
FastjsonUtil.writeJSONWithDateFormatAndIncludes(ServletActionContext.getResponse(),book, null, "id,publishDate");
- 把json字符串反序列化爲java對象
//把json字符串轉換爲Book對象
String json_book="{'book_name':'西遊記','id':1,'publishDate':'2012/12/1 12:25:11'}";
Book book=FastjsonUtil.parseObject(json_book, Book.class);
//把json字符串轉換爲Book泛型集合
String json_list="[{'book_name':'西遊記','id':1},{'book_name':'紅樓夢','id':2}]";
//第二個參數不要漏了大括號{},泛型類跟返回值類型是一樣的,其他都是固定寫法
List<Book> list=FastjsonUtil.parseObject(json_list,new TypeReference<List<Book>>(){});