json转换fastjson

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 筛选属性

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>>(){});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章