Jackson、Gson和Fastjson序列化、反序列化示例
import java.lang.reflect.Type;
import java.util.Date;
import com.alibaba.fastjson.JSON;
import com.example.tooltest.bean.DemoBean;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.time.LocalDateTime;
@Slf4j
public class JsonSerializableTests {
private static DemoBean bean;
private static List<Map<String, DemoBean>> list;
@BeforeAll
static void init() {
bean = new DemoBean();
bean.setId(1000);
bean.setContext("我是内容");
bean.setCreateTime(new Date());
bean.setUpdateTime(LocalDateTime.now());
list = new ArrayList<>();
for (int i = 0; i < 6; i++) {
Map<String, DemoBean> map = new HashMap<>();
for (int j = 0; j < 2; j++) {
int num = Integer.parseInt(i + "" + j);
DemoBean demoBean = new DemoBean();
demoBean.setId(num);
demoBean.setContext("我是内容" + num);
demoBean.setCreateTime(new Date());
demoBean.setUpdateTime(LocalDateTime.now());
map.put(String.valueOf(num), demoBean);
}
list.add(map);
}
}
@Test
void testFastJson() {
String simpleSerialize = JSON.toJSONString(bean);
DemoBean simpleDeserialize = JSON.parseObject(simpleSerialize, DemoBean.class);
String complexSerialize = JSON.toJSONString(list);
com.alibaba.fastjson.TypeReference<List<Map<String, DemoBean>>> typeReference =
new com.alibaba.fastjson.TypeReference<List<Map<String, DemoBean>>>(){};
List<Map<String, DemoBean>> complexDeserialize = JSON.parseObject(complexSerialize, typeReference);
}
@Test
void testGson() {
Gson gson = new Gson();
String simpleSerialize = gson.toJson(bean);
DemoBean simpleDeserialize = gson.fromJson(simpleSerialize, DemoBean.class);
String complexSerialize = gson.toJson(list);
Type type = new TypeToken<List<Map<String, DemoBean>>>() {}.getType();
List<Map<String, DemoBean>> complexDeserialize = gson.fromJson(complexSerialize, type);
}
@Test
void testJackson() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
String simpleSerialize = mapper.writeValueAsString(bean);
DemoBean simpleDeserialize = mapper.readValue(simpleSerialize, DemoBean.class);
String complexSerialize = mapper.writeValueAsString(list);
com.fasterxml.jackson.core.type.TypeReference<List<Map<String, DemoBean>>> typeReference =
new com.fasterxml.jackson.core.type.TypeReference<List<Map<String, DemoBean>>>(){};
List<Map<String, DemoBean>> complexDeserialize = mapper.readValue(complexSerialize, typeReference);
}
}
@Data
public class DemoBean {
private Integer id;
private String context;
private Date createTime;
private LocalDateTime updateTime;
}