fastjson


java bean序列化为json字符串,json字符串反序列化为java bean


优点:


    • 速度快
    • 使用简单
    • 功能完备
      支持泛型,支持流处理超大文本,支持枚举,支持序列化和反序列化扩展
导包

<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>

springboot中的配置

MyWebMvcConfig

@Bean
public HttpMessageConverter configureMessageConverters() {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(
// 保留map空的字段
SerializerFeature.WriteMapNullValue,
// 将String类型的null转成""
SerializerFeature.WriteNullStringAsEmpty,
// 将Number类型的null转成0
SerializerFeature.WriteNullNumberAsZero,
// 将List类型的null转成[]
SerializerFeature.WriteNullListAsEmpty,
// 将Boolean类型的null转成false
SerializerFeature.WriteNullBooleanAsFalse,
// 避免循环引用
SerializerFeature.DisableCircularReferenceDetect);

converter.setFastJsonConfig(config);
converter.setDefaultCharset(Charset.forName("UTF-8"));
List<MediaType> mediaTypeList = new ArrayList<>();
// 解决中文乱码问题,相当于在Controller上的@RequestMapping中加了个属性produces = "application/json"
mediaTypeList.add(MediaType.APPLICATION_JSON);
converter.setSupportedMediaTypes(mediaTypeList);
return converter;
}

 


对象和json的转换

// 对象
User user1 = new User(11, "lisi");
User user2 = new User(12, "zhangsan");
String s = JSON.toJSONString(user1);
System.out.println("对象变为json字符串" + s);
User user = JSON.parseObject(s, User.class);
System.out.println("json字符串变为对象" + user);

JSONObject jsonObject = (JSONObject)JSON.toJSON(user1);
System.out.println("java对象变为json对象" + jsonObject);
User user3 = JSON.toJavaObject(jsonObject, User.class);
System.out.println("json对象变为java对象" + user3);


// list
List list = new ArrayList();
list.add(user1);
list.add(user2);
String s1 = JSON.toJSONString(list);
System.out.println("list变为json字符串" + s1);// []是个数组
List<User> users = JSON.parseArray(s1, User.class);
System.out.println("json字符串变为list" + users);

// map
Map map = new HashMap();
map.put("user1", user1);
map.put("user2", user2);
String smap = JSON.toJSONString(map);
System.out.println("map变为json字符串" + smap);
Map<String, Student> map = JSON.parseObject(smp, new TypeReference<Map<String, User>>());
System.out.println("json字符串变为map" + users);




JSONObject

JSONObject jsonObject = new JSONObject();
jsonObject.put("userName", "中文");
jsonObject.put("password", "1 + 1");
// JSONObject 转为json字符串
jsonObject.toJSONString();

// JSONObject转为map
Map<String,String> = jsonObject.parseObject(jsonObject.toJSONString(), new TypeReference<Map<String,String>>);


SerializerFeature

枚举常量个性化定制   

空双引号


 

 

 将空integer赋值为0

 

 日期格式化

 

 

 

 一对对的pretty格式

 

 

 

 

public class FastjsonTest {
public static void main(String[] args) {
UserRequest u1 = new UserRequest();
u1.setId(1L);
u1.setPassword("u1");
String s = JSON.toJSONString(u1);
System.out.println(s);
}
}
// {"id":1,"password":"u1"} 为null的 不会被序列化为json字符串



// 序列化null
// {"id":1,"password":"u1","userName":null}
String s = JSON.toJSONString(u1, SerializerFeature.WriteMapNullValue);



// 序列化为""
// {"id":1,"password":"u1","userName":""}
String s = JSON.toJSONString(u1, SerializerFeature.WriteNullStringAsEmpty);


// 序列化 number 为0
public static void main(String[] args) {
UserRequest u1 = new UserRequest();
u1.setPassword("u1");
String s = JSON.toJSONString(u1, SerializerFeature.WriteNullNumberAsZero);
System.out.println(s);
}
// {"id":0,"password":"u1"}


WriteNullBooleanAsFalse // 属性为Boolean的没有值 则被序列化为false
WriteDateUseDateFormat // 将原来的日期序列化为 年月日时分秒


// 显示Pretty格式化
public static void main(String[] args) {
UserRequest u1 = new UserRequest();
u1.setPassword("u1");
String s = JSON.toJSONString(u1, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.PrettyFormat);
System.out.println(s);
}
/*
{
"id":0,
"password":"u1"
}
*/


 ------------------------------- ------------------------------- ------------------------------- -------------------------------

 
public class Student {
private Integer id;
private String name;
private Integer age;
private String email;
private Date birthday;
}


public class fastJson {


public Date getDate() {
Date date = new Date();
return date;
}

@Test
public void testObjtoJson() {
Student student = new Student();
student.setAge(19);
student.setName("zzz");
student.setId(1);
student.setEmail("88.com");
student.setBirthday(getDate());
String s = JSON.toJSONString(student);
System.out.println(s);
}

@Test
public void testListToJson() {
Student student1 = new Student();
student1.setAge(19);
student1.setName("zzz");
student1.setId(1);
student1.setEmail("88.com");
student1.setBirthday(getDate());

Student student2 = new Student();
student2.setAge(20);
student2.setName("zzz2");
student2.setId(2);
student2.setEmail("99.com");
student2.setBirthday(getDate());
List<Student> list = new ArrayList<Student>();
list.add(student1);
list.add(student2);
String s = JSON.toJSONString(list);
System.out.println(s);
}
@Test
public void testMapToJson(){
Student student1 = new Student();
student1.setAge(19);
student1.setName("zzz");
student1.setId(1);
student1.setEmail("88.com");
student1.setBirthday(getDate());

Student student2 = new Student();
student2.setAge(20);
student2.setName("zzz2");
student2.setId(2);
student2.setEmail("99.com");
student2.setBirthday(getDate());
HashMap<String, Student> map = new HashMap<>();
map.put("s1",student1);
map.put("s2",student2);
String s = JSON.toJSONString(map);
System.out.println(s);

}
@Test
public void testJsonToObj() {
String obj = "{\"age\":19,\"birthday\":1652368762320,\"email\":\"88.com\",\"id\":1,\"name\":\"zzz\"}\n";
Student student = JSON.parseObject(obj, Student.class);
Student student1 = JSONObject.parseObject(obj, Student.class);
System.out.println(student);
System.out.println(student1);
}

@Test
public void testListToObj() {
String obj = "[{\"age\":19,\"birthday\":1652369165457,\"email\":\"88.com\",\"id\":1,\"name\":\"zzz\"},{\"age\":20,\"birthday\":1652369165457,\"email\":\"99.com\",\"id\":2,\"name\":\"zzz2\"}]\n";
// Student student = JSON.parseObject(obj, Student.class);
// Student student1 = JSONObject.parseObject(obj, Student.class);
// System.out.println(student);
// System.out.println(student1);
List<Student> students = JSON.parseArray(obj, Student.class);
List<Student> students2 = JSONObject.parseArray(obj, Student.class);
System.out.println(students);
System.out.println(students2);
}

@Test
public void testMapToObj() {
String obj = "{\"s1\":{\"age\":19,\"birthday\":1652369958048,\"email\":\"88.com\",\"id\":1,\"name\":\"zzz\"},\"s2\":{\"age\":20,\"birthday\":1652369958048,\"email\":\"99.com\",\"id\":2,\"name\":\"zzz2\"}}\n";
Map map = JSON.parseObject(obj);
Map map2 = JSONObject.parseObject(obj);
Map<String, Student> stringStudentMap = JSON.parseObject(obj, new TypeReference<Map<String, Student>>(){});
Map<String, Student> stringStudentMap5 = JSON.parseObject(obj, new TypeReference<Map<String, Student>>(){});
Map<String, Student> contentMap = new HashMap<>();
Map<String, Student> stringStudentMap2 = (Map<String, Student>) JSONObject.parseObject(obj, contentMap.getClass());
for(String key: stringStudentMap.keySet()){
System.out.println(key+"::"+stringStudentMap.get(key));
}
for(String key2: stringStudentMap5.keySet()){
System.out.println(key2+"::"+stringStudentMap5.get(key2));
}
}
}
posted @   lamda表达式先驱  阅读(144)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示