1 FastJson

fastjson quick start cn

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>fastjson</artifactId>
  4. <version>x.x.x</version>
  5. </dependency>

kimmking:JSON Best Practice(最佳实践)

1.1 SerializerFeature属性

名称 含义 备注
QuoteFieldNames 输出key时是否使用双引号,默认为true
UseSingleQuotes 使用单引号而不是双引号,默认为false
WriteMapNullValue 是否输出值为null的字段,默认为false
WriteEnumUsingToString Enum输出name()或者original,默认为false
UseISO8601DateFormat Date使用ISO8601格式输出,默认为false
WriteNullListAsEmpty List字段如果为null,输出为[],而非null
WriteNullStringAsEmpty 字符类型字段如果为null,输出为”“,而非null
WriteNullNumberAsZero 数值字段如果为null,输出为0,而非null
WriteNullBooleanAsFalse Boolean字段如果为null,输出为false,而非null
SkipTransientField 如果是true,类中的Get方法对应的Field是transient,序列化时将会被忽略。默认为true
SortField 按字段名称排序后输出。默认为false
WriteTabAsSpecial 把\t做转义输出,默认为false 不推荐
PrettyFormat 结果是否格式化,默认为false
WriteClassName 序列化时写入类型信息,默认为false。反序列化是需用到
DisableCircularReferenceDetect 消除对同一对象循环引用的问题,默认为false
WriteSlashAsSpecial 对斜杠’/’进行转义
BrowserCompatible 将中文都会序列化为\uXXXX格式,字节数会多一些,但是能兼容IE 6,默认为false
WriteDateUseDateFormat 全局修改日期格式,默认为false。JSON.DEFFAULT_DATE_FORMAT = “yyyy-MM-dd”;JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);
DisableCheckSpecialChar 一个对象的字符串属性中如果有特殊字符如双引号,将会在转成json时带有反斜杠转移符。如果不需要转义,可以使用这个属性。默认为false
NotWriteRootClassName 含义
BeanToArray 将对象转为array输出
WriteNonStringKeyAsString 含义
NotWriteDefaultValue 含义
BrowserSecure 含义
IgnoreNonFieldGetter 含义
WriteEnumUsingName 含义

1.2 $ref 的错误

设置一下序列化特性,DisableCircularReferenceDetect 即可。

2 对象转换(拷贝)

对象转换,都是找到的对应字段的映射关系。这个涉及到字段的类型,字段访问权限(private、protected等) ,特殊类型(日期等);
另外一点,就是深拷贝,浅拷贝问题,不同的转换采取的方式不同。

2.1 org.apache.commons.beanutils.PropertyUtils

http://commons.apache.org/proper/commons-beanutils/

2.2 org.springframework.beans.BeanUtils

2.3 Bull(Bean Utils Light Library)

https://github.com/ExpediaGroup/bull

2.4 Dozer

http://dozer.sourceforge.net/

  1. <dependency>
  2. <groupId>net.sf.dozer</groupId>
  3. <artifactId>dozer</artifactId>
  4. <version>5.4.0</version>
  5. </dependency>

2.5 mapstruct

https://github.com/mapstruct/mapstruct/
https://mapstruct.org/

  1. ...
  2. <properties>
  3. <org.mapstruct.version>1.4.2.Final</org.mapstruct.version>
  4. </properties>
  5. ...
  6. <dependencies>
  7. <dependency>
  8. <groupId>org.mapstruct</groupId>
  9. <artifactId>mapstruct</artifactId>
  10. <version>${org.mapstruct.version}</version>
  11. </dependency>
  12. </dependencies>
  13. ...
  14. <build>
  15. <plugins>
  16. <plugin>
  17. <groupId>org.apache.maven.plugins</groupId>
  18. <artifactId>maven-compiler-plugin</artifactId>
  19. <version>3.8.1</version>
  20. <configuration>
  21. <source>1.8</source>
  22. <target>1.8</target>
  23. <annotationProcessorPaths>
  24. <path>
  25. <groupId>org.mapstruct</groupId>
  26. <artifactId>mapstruct-processor</artifactId>
  27. <version>${org.mapstruct.version}</version>
  28. </path>
  29. </annotationProcessorPaths>
  30. </configuration>
  31. </plugin>
  32. </plugins>
  33. </build>
  34. ...

2.6 Jackson Data Bind

https://github.com/FasterXML/jackson-databind

  1. <dependency>
  2. <groupId>com.fasterxml.jackson.core</groupId>
  3. <artifactId>jackson-databind</artifactId>
  4. <version>${jackson.version}</version>
  5. </dependency>

2.7 modelmapper

http://modelmapper.org/getting-started/
https://github.com/modelmapper/modelmapper
java 8

  1. <dependency>
  2. <groupId>org.modelmapper</groupId>
  3. <artifactId>modelmapper</artifactId>
  4. <version>2.4.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.github.jmnarloch</groupId>
  8. <artifactId>modelmapper-spring-boot-starter</artifactId>
  9. <version>1.1.0</version>
  10. </dependency>

modelMapper 主要考虑匹配策略和隐式匹配,不同的规则不同。

3 hutools

https://www.hutool.cn/

模块 介绍 备注
hutool-aop JDK动态代理封装,提供非IOC下的切面支持
hutool-bloomFilter 布隆过滤,提供一些Hash算法的布隆过滤
hutool-cache 简单缓存实现
hutool-core 核心,包括Bean操作、日期、各种Util等
hutool-cron 定时任务模块,提供类Crontab表达式的定时任务
hutool-crypto 加密解密模块,提供对称、非对称和摘要算法封装
hutool-db JDBC封装后的数据操作,基于ActiveRecord思想
hutool-dfa 基于DFA模型的多关键字查找
hutool-extra 扩展模块,对第三方封装(模板引擎、邮件、Servlet、二维码、Emoji、FTP、分词等)
hutool-http 基于HttpUrlConnection的Http客户端封装
hutool-log 自动识别日志实现的日志门面
hutool-script 脚本执行封装,例如Javascript 不推荐
hutool-setting 功能更强大的Setting配置文件和Properties封装
hutool-system 系统参数调用封装(JVM信息等)
hutool-json JSON实现
hutool-captcha 图片验证码实现
hutool-poi 针对POI中Excel和Word的封装
hutool-socket 基于Java的NIO和AIO的Socket封装
hutool-jwt JSON Web Token (JWT)封装实现
NotWriteRootClassName 含义
BeanToArray 将对象转为array输出
WriteNonStringKeyAsString 含义
NotWriteDefaultValue 含义
BrowserSecure 含义
IgnoreNonFieldGetter 含义
WriteEnumUsingName 含义

4 easyExcel

https://github.com/alibaba/easyexcel/
https://www.yuque.com/easyexcel/doc/easyexcel
https://alibaba-easyexcel.github.io/

5 spring 内置的工具类

主要是 spring-boot-starter 中的
https://spring.io/blog/2021/01/27/ymnnalft-the-spring-utils-classes

  1. package bootiful.utils;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.extern.log4j.Log4j2;
  5. import org.springframework.aop.support.AopUtils;
  6. import org.springframework.beans.BeanUtils;
  7. import org.springframework.boot.SpringApplication;
  8. import org.springframework.boot.autoconfigure.SpringBootApplication;
  9. import org.springframework.boot.context.event.ApplicationReadyEvent;
  10. import org.springframework.context.ApplicationListener;
  11. import org.springframework.context.annotation.Bean;
  12. import org.springframework.core.ResolvableType;
  13. import org.springframework.core.io.ClassPathResource;
  14. import org.springframework.core.io.Resource;
  15. import org.springframework.jmx.support.JmxUtils;
  16. import org.springframework.stereotype.Component;
  17. import org.springframework.util.*;
  18. import javax.annotation.PostConstruct;
  19. import java.beans.PropertyDescriptor;
  20. import java.io.InputStreamReader;
  21. import java.io.Reader;
  22. import java.io.Serializable;
  23. import java.lang.reflect.Constructor;
  24. import java.lang.reflect.Field;
  25. import java.util.*;
  26. @Log4j2
  27. @SpringBootApplication
  28. public class BootifulApplication {
  29. @Data
  30. @AllArgsConstructor
  31. @Component
  32. public static class DemoClass {
  33. @PostConstruct
  34. public void begin() {
  35. log.info("begin()");
  36. }
  37. private final List<Map<String, Object>> list = new ArrayList<>();
  38. }
  39. @Bean
  40. ApplicationListener<ApplicationReadyEvent> ready(DemoClass demo) {
  41. return event -> {
  42. Assert.notNull(demo.getList(), "the list can't be null");
  43. beansUtils(demo);
  44. classUtils();
  45. systemPropertyUtils();
  46. fileCopyUtils();
  47. aop(demo);
  48. reflection();
  49. ensure();
  50. collections();
  51. serialize();
  52. };
  53. }
  54. private void ensure() {
  55. int counter = 2;
  56. Assert.state(counter == 2, () -> "the counter should be 2 or more. Was " + counter);
  57. Assert.hasText("Hello, world!", () -> "this string should be a non-null, non-empty String");
  58. }
  59. private void reflection() {
  60. ReflectionUtils.doWithFields(DemoClass.class, field -> log.info("field = " + field.toString()));
  61. ReflectionUtils.doWithMethods(DemoClass.class, method -> log.info("method = " + method.toString()));
  62. Field list = ReflectionUtils.findField(DemoClass.class, "list");
  63. log.info(Objects.requireNonNull(list).toString());
  64. ResolvableType rt = ResolvableType.forField(list);
  65. log.info(rt.toString());
  66. }
  67. private void aop(DemoClass demoClass) {
  68. Class<?> targetClass = AopUtils.getTargetClass(demoClass);
  69. log.info("Class<?> is " + targetClass);
  70. log.info("is AOP proxy? " + AopUtils.isAopProxy(demoClass));
  71. log.info("is CGlib proxy? " + AopUtils.isCglibProxy(demoClass));
  72. }
  73. private void collections() {
  74. Collection<String> names = Arrays.asList("Tammie", "Kimly", "Josh");
  75. boolean contains = CollectionUtils.containsAny(names, Arrays.asList("Josh"));
  76. Assert.state(contains, () -> "one or more of the names in " + names.toString() + " should be present");
  77. }
  78. private void serialize() {
  79. Customer in = new Customer(593232329, "Josh");
  80. byte[] bytes = SerializationUtils.serialize(in);
  81. Customer out = (Customer) SerializationUtils.deserialize(bytes);
  82. Assert.state(out.getId() == in.getId() && out.getName().equals(in.getName()),
  83. () -> "the " + Customer.class.getName() + " did not serialize correctlyy");
  84. }
  85. private void fileCopyUtils() {
  86. Resource cpr = new ClassPathResource("/application.properties");
  87. try (Reader r = new InputStreamReader(cpr.getInputStream())) {
  88. String contents = FileCopyUtils.copyToString(r);
  89. log.info("application.properties contents: " + contents);
  90. }
  91. catch (Exception e) {
  92. throw new RuntimeException(e);
  93. }
  94. }
  95. private void systemPropertyUtils() {
  96. String resolvedText = SystemPropertyUtils.resolvePlaceholders("my home directory is ${user.home}");
  97. log.info("resolved text: " + resolvedText);
  98. }
  99. private void classUtils() {
  100. Constructor<DemoClass> demoClassConstructor = ClassUtils.getConstructorIfAvailable(DemoClass.class);
  101. log.info("demoClassConstructor: " + demoClassConstructor);
  102. try {
  103. DemoClass demoClass = demoClassConstructor.newInstance();
  104. log.info("newInstance'd demoClass: " + demoClass);
  105. }
  106. catch (Exception e) {
  107. throw new RuntimeException(e);
  108. }
  109. }
  110. private void beansUtils(DemoClass demo) {
  111. PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(demo.getClass());
  112. for (PropertyDescriptor pd : descriptors) {
  113. log.info("pd: " + pd.getName());
  114. }
  115. }
  116. public static void main(String[] args) {
  117. SpringApplication.run(BootifulApplication.class, args);
  118. }
  119. }
  120. @Data
  121. class Customer implements Serializable {
  122. static final long serialVersionUID = 1L;
  123. private int id;
  124. private String name;
  125. public Customer(int id, String name) {
  126. this.id = id;
  127. this.name = name;
  128. }
  129. }

相关的工具类:

  • BeanUtils - useful functions for dealing with JavaBeans
  • ClassUtils - useful functions for asking questions reflectively about types
  • SystemPropertyUtils - useful functions for dealing with System properties
  • FileCopyUtils - useful functions for copying InputStream and OutputStream implementations
  • AopUtils - useful functions for dealing with Spring’s AOP proxies
  • ReflectionUtils - useful functions for dealing with reflection, broadly
  • Assert - useful functions to help with design-by-contract-style assertions
  • CollectionUtils - useful functions for working various Java java.util.Collection types
  • SerializeUtils - useful functions for working with Java serialization