fastjson泛型序列化

1、需要序列化类

/**   
 * @Title: ReqIn.java 
 * @Package com.spring.pro.utils.fastjson 
 * @Description:  
 * @author ybwei  
 * @date 2018年10月8日 上午11:23:44 
 * @version V1.0   
 */
public class ReqIn {

	private String token;
	private T data;
	
	public ReqIn(String token, T data) {
		super();
		this.token = token;
		this.data = data;
	}
	public ReqIn() {
		super();
	}
	public String getToken() {
		return token;
	}
	public void setToken(String token) {
		this.token = token;
	}
	public T getData() {
		return data;
	}
	public void setData(T data) {
		this.data = data;
	}
}

2、定义model

/**   
 * @Title: User.java 
 * @Package com.spring.pro.utils.fastjson 
 * @Description:  
 * @author ybwei  
 * @date 2018年10月8日 上午11:26:10 
 * @version V1.0   
 */
public class User {

	private String id;
	private int age;
	
	
	public User() {
		super();
	}
	public User(String id, int age) {
		super();
		this.id = id;
		this.age = age;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

3、测试

import java.lang.reflect.Type;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

/**
 * @Title: GenericityTest.java
 * @Package com.spring.pro.utils.fastjson
 * @Description:
 * @author ybwei
 * @date 2018年10月8日 上午11:21:50
 * @version V1.0
 */
public class GenericityTest {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Test
	public void parseObject() {
		User user = new User("1", 12);
		ReqIn req = new ReqIn<>("token", user);
		String str = JSON.toJSONString(req);
		logger.info("str:{}", str);
		
		Type type = new TypeReference>() {}.getType();
		ReqIn req2 = JSON.parseObject(str, type);
		logger.info("req2:{}",JSON.toJSONString(req2));
	}
}

 

你可能感兴趣的:(java)