浅谈Java中FastJson的使用

2025-05-29 0 88

FastJson的使用

使用maven导入依赖包

  1. <!–下边依赖跟aop没关系,只是项目中用到了 JSONObject,所以引入fastjson–>
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>fastjson</artifactId>
  5. <version>1.2.70</version>
  6. </dependency>

常用方法:

1.JSON.toJSONString(obejct) – java对象转JSON字符串,

注意:

默认情况下,如果int类型和boolean类型的属性没赋值的时候(public boolean a; public int b;),调用 JSON.toJSONString(obejct) 序列化后,a和b不会被过滤掉,而是返回boolean类型和int类型的默认值 false和0。当然其他类型如果没有赋值,序列化时,会被过滤掉。

来看下例子就明白了

  1. public class Test {
  2. public static void main(String[] args) {
  3. List<User> userList = new ArrayList<>();
  4. User user = new User();
  5. user.setName("123");
  6. userList.add(user);
  7. System.out.println(JSON.toJSONString(userList));
  8. }
  9. public static class User{
  10. private String name;
  11. private int age;
  12. public boolean health;
  13. public Date time;
  14. public String getName() {
  15. return name;
  16. }
  17. public void setName(String name) {
  18. this.name = name;
  19. }
  20. public int getAge() {
  21. return age;
  22. }
  23. public void setAge(int age) {
  24. this.age = age;
  25. }
  26. }
  27. }

先给name赋值,其他的都不赋值,结果time属性被过滤掉了,如下:

浅谈Java中FastJson的使用

再看下都不赋值的情况,结果name和time属性都被过滤掉了,而int类型的age和boolean类型的health属性取得时类型的默认值:

浅谈Java中FastJson的使用

2.JSON.parseObject(string, User.class) – JSON字符串转java对象

(1)List集合转JSON

  1. @RestController
  2. public class Json {
  3. @RequestMapping(value = "/json")
  4. public String json() throws Exception{
  5. List<User> userList = new ArrayList<>();
  6. userList.add(new User("1", "1", 20));
  7. String res = JSON.toJSONString(userList);
  8. return res;
  9. }
  10. }

浅谈Java中FastJson的使用

(2)Map集合转JSON

  1. package com.lxc.Test;
  2. import com.alibaba.fastjson.JSON;
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import java.util.Map;
  7. public class Json {
  8. public static void main(String[] args) {
  9. Map<String, Object> userList = new HashMap<>();
  10. for(int i = 0; i < 5; i ++) {
  11. userList.put("user"+i, new User("name"+i, 20+i));
  12. }
  13. System.out.println("json:"+JSON.toJSONString(userList));
  14. }
  15. public static class User{
  16. private String name;
  17. private int age;
  18. public User(String name, int age) {
  19. this.name = name;
  20. this.age = age;
  21. }
  22. public String getName() {
  23. return name;
  24. }
  25. public void setName(String name) {
  26. this.name = name;
  27. }
  28. public int getAge() {
  29. return age;
  30. }
  31. public void setAge(int age) {
  32. this.age = age;
  33. }
  34. }
  35. }

浅谈Java中FastJson的使用

反序列化

1.JSON转Java对象 – JSON.perseObject()

  1. public class Json {
  2. public static void main(String[] args) {
  3. String json = "{\\"age\\":20,\\"name\\":\\"name0\\"}";
  4. System.out.println(JSON.parseObject(json, User.class)+"");
  5. }
  6. }

浅谈Java中FastJson的使用

2.JSON转Java集合- JSON.perseArray()

  1. public class Json {
  2. public static void main(String[] args) {
  3. String json = "[{\\"age\\":20,\\"name\\":\\"name0\\"}]";
  4. List<User> userList = JSON.parseArray(json, User.class);
  5. userList.forEach(System.out::println);
  6. }
  7. }

浅谈Java中FastJson的使用

JSON.toJSONString() 参数 –SerializerFeature枚举常量

toJSONString静态方法参数有两个:

参数一:要序列化的对象;
参数二:SerializerFeature 枚举类型的可变参数 ( 我们可以传递多个参数 ),进行序列化时,我们可以定义特殊的需求。

浅谈Java中FastJson的使用

1.SerializerFeature.WriteMapNullValue

对一个对象或者列表进行序列化时,默认情况下如果属性值为null,序列化后的结果会过滤掉其属性,如果想保留其属性值,可以使用 SerializerFeature.WriteMapNullValue。

  1. public class Json {
  2. public static void main(String[] args) {
  3. User user = new User();
  4. user.setAge(20);
  5. String res = JSON.toJSONString(user, SerializerFeature.WriteMapNullValue);
  6. System.out.println(res);
  7. }
  8. public static class User{
  9. private String name = null;
  10. private int age;
  11. public String getName() {
  12. return name;
  13. }
  14. public void setName(String name) {
  15. this.name = name;
  16. }
  17. public int getAge() {
  18. return age;
  19. }
  20. public void setAge(int age) {
  21. this.age = age;
  22. }
  23. @Override
  24. public String toString() {
  25. return "User{" +
  26. "name='" + name + '\\'' +
  27. ", age=" + age +
  28. '}';
  29. }
  30. }
  31. }

浅谈Java中FastJson的使用

2.SerializerFeature.WriteNullStringAsEmpty

对一个对象或者列表进行序列,把属性值为null的字段进行转化为 "" 双引号。

  1. public class Json {
  2. public static void main(String[] args) {
  3. User user = new User();
  4. user.setAge(20);
  5. String res = JSON.toJSONString(user, SerializerFeature.WriteNullStringAsEmpty);
  6. System.out.println(res);
  7. }
  8. }

浅谈Java中FastJson的使用

3.SerializerFeature.WriteNullNumberAsZero

序列之后, 把属性值为 null 的属性转化为 0,这个前提是此属性是 int 类型的!

  1. public class Json {
  2. public static void main(String[] args) {
  3. User user = new User();
  4. user.setName("测试");
  5. String res = JSON.toJSONString(user, SerializerFeature.WriteNullNumberAsZero);
  6. System.out.println(res);
  7. }
  8. }

浅谈Java中FastJson的使用

4.SerializerFeature.WriteNullBooleanAsFalse

序列之后, 把属性值为 null 的属性转化为 false,这个前提是此属性是 boolean 类型的!

  1. @Data
  2. public class User{
  3. private String name;
  4. private int age;
  5. private boolean health;
  6. }

浅谈Java中FastJson的使用

5.SerializerFeature.WriteDateUseDateFormat

把时间戳序列化为正常的时间,默认输出JSON.toJSONString()序列之后, 默认输出如下:

浅谈Java中FastJson的使用

添加SerializerFeature.WriteDateUseDateFormat之后的效果:

浅谈Java中FastJson的使用

  1. @Data
  2. public class User{
  3. private String name;
  4. private int age;
  5. private Date birthday = new Date();
  6. private boolean health;
  7. }

6.SerializerFeature.PrettyFormat

序列化的数据纵向布局。

浅谈Java中FastJson的使用

@JSonField() 注解

在序列化时,进行个性定制!该注解的作用于方法上,字段上、参数上,可在序列化和反序列化时进行特性功能定制。

浅谈Java中FastJson的使用

1.注解属性 name序列化后的名字(单独序列化,对属性名进行修改)

  1. @JSONField(name="username")
  2. private String name;

浅谈Java中FastJson的使用

2.注解属性 ordinal序列化后的顺序(字段的排序)

  1. @JSONField(ordinal = 1)
  2. private String name;
  3. @JSONField(ordinal = 2)
  4. private int age;

浅谈Java中FastJson的使用

3.注解属性 format序列化后的格式

  1. @JSONField(format = "YYYY-MM-dd")
  2. private Date birthday = new Date();

浅谈Java中FastJson的使用

4.注解属性 serialize 是否序列化该字段(默认为true,如果false,当字段值为null时,会被过滤掉)

5.使用serializeUsing来定制属性的序列化类

浅谈Java中FastJson的使用

什么意思呢,类似vue中的过滤器,可以单独订制处理类下的某个属性:

第一步:编写一个类A,实现ObjectSerializer 接口;
第二步:重写write方法;
第三步:在需要定制化的属性上边 添加注解,@JSONField(serializeUsing = A.class)

具体实现如下:

  1. public class Json {
  2. public static void main(String[] args) {
  3. List<User> userList = new ArrayList<>();
  4. User user = new User();
  5. user.setName("测试,");
  6. userList.add(user);
  7. System.out.println(JSON.toJSONString(userList));
  8. }
  9. public static class SerializeUsingFn implements ObjectSerializer {
  10. @Override
  11. public void write(JSONSerializer jsonSerializer, Object fieldValue, Object fieldName, Type fieldType, int i) throws IOException {
  12. System.out.println(fieldValue); // 测试,
  13. System.out.println(fieldName); // name
  14. System.out.println(fieldType); // String
  15. System.out.println(i); // 0
  16. String name = (String) fieldValue; // 向下转型,获取到age属性值
  17. String filterName = name + "呵呵"; // 这里可以对name属性进行定制化
  18. jsonSerializer.write(filterName); // 调用write方法
  19. }
  20. }
  21. public static class User{
  22. @JSONField(serializeUsing = SerializeUsingFn.class)
  23. private String name;
  24. private int age;
  25. public boolean health;
  26. public Date time;
  27. public String getName() {
  28. return name;
  29. }
  30. public void setName(String name) {
  31. this.name = name;
  32. }
  33. public int getAge() {
  34. return age;
  35. }
  36. public void setAge(int age) {
  37. this.age = age;
  38. }
  39. }
  40. }

可以看到name字段值 被修改了后边添加了 "呵呵" 俩字。

浅谈Java中FastJson的使用

@JSONType() 注解

只能作用在类上,也是对类里边的字段进行序列化

浅谈Java中FastJson的使用

@JSONType()注解中的属性

· includes 要序列化的字段(注意:如果字段上有@serialize(true),如果没有includes字段也不会被序列化),它是一个数组,源码如下:

浅谈Java中FastJson的使用

  1. @Data
  2. @JSONType(includes = {"name", "age"})
  3. public class User{
  4. private String name;
  5. private int age;
  6. private boolean health;
  7. private Date birthday = new Date();
  8. }

浅谈Java中FastJson的使用

·orders序列化后的字段顺序,也是一个数组,源码如下:

浅谈Java中FastJson的使用

  1. @JSONType(includes = {"name","birthday", "health", "age"}, orders = {"age","name","birthday","health"})
  2. public static class User{
  3. private String name;
  4. private int age;
  5. private boolean health;
  6. private Date birthday = new Date();
  7. }

浅谈Java中FastJson的使用

FastJson属性名过滤器

过滤字段,通过SimplePropertyPreFilter 过滤器,来过滤指定的属性名,然后在转JSON的时候,带上过滤器参数即可。
例如,把下边属性health 过滤掉:

  1. // userList = [{"age":20,"health":true,"name":"测试,呵呵","time":"2021-06-29 09:40:55"}]
  2. SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
  3. // 下边方法也很好理解:调用过滤器上边的getExcludes排除字段的方法,什么字段需要排除呢:add() 添加需要排除的字段即可
  4. filter.getExcludes().add("health");
  5. System.out.println(JSON.toJSONString(userList, filter));

浅谈Java中FastJson的使用

当然,如果需要排除大量的字段,保留一个字段,可以使用:filter.getIncludes() .add("xxx") 方法,意思:只保留xxx属性,其他的都会被过滤。

如果过滤或者添加多个字段,可以使用:addAll() 方法,参数必须是一个集合Collection 。

浅谈Java中FastJson的使用

过滤多个字段:

  1. SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
  2. List<String> r = new ArrayList<>() {
  3. {
  4. add("health");
  5. add("name");
  6. }
  7. };
  8. filter.getExcludes().addAll(r);
  9. System.out.println(JSON.toJSONString(userList, filter));

浅谈Java中FastJson的使用

暂时就这么多,项目中用到别的方法在记录!

到此这篇关于浅谈Java中FastJson的使用的文章就介绍到这了,更多相关FastJson的使用内容请搜索快网idc以前的文章或继续浏览下面的相关文章希望大家以后多多支持快网idc!

原文链接:https://blog.csdn.net/qq_42778001/article/details/118342878

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 浅谈Java中FastJson的使用 https://www.kuaiidc.com/105383.html

相关文章

发表评论
暂无评论