JAVA JSON XML ZIP介绍
2026/6/11 9:23:10 网站建设 项目流程

ZIP压缩与解压

/** * 压缩文件 */ import java.util.Objects; import lombok.extern.slf4j.Slf4j; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.utils.IOUtils; import java.io.*; import java.util.Arrays; import java.util.List; @Slf4j public class ZipUtils { private ZipUtils() { // 私用构造主法.因为此类是工具类. } static int bufferSize = 8192;//单位bytes /** * 用于单文件压缩 */ public static void doCompress(File srcFile, File destFile) throws IOException { ZipArchiveOutputStream out = null; InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(srcFile), bufferSize); out = new ZipArchiveOutputStream(new BufferedOutputStream(new FileOutputStream(destFile), bufferSize)); ZipArchiveEntry entry = new ZipArchiveEntry(srcFile.getName()); entry.setSize(srcFile.length()); out.putArchiveEntry(entry); IOUtils.copy(is, out); out.closeArchiveEntry(); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(out); } } /** * 用于多文件压缩 */ public static File doCompressFiles(List<File> srcFiles, File destFile) throws IOException { if (Objects.nonNull(srcFiles) && srcFiles.size() == 1) { return srcFiles.get(0); } ZipArchiveOutputStream out = null; InputStream is = null; try { out = new ZipArchiveOutputStream(new BufferedOutputStream(new FileOutputStream(destFile), bufferSize)); for (File srcFile : srcFiles) { is = new BufferedInputStream(new FileInputStream(srcFile), bufferSize); ZipArchiveEntry entry = new ZipArchiveEntry(srcFile.getName()); entry.setSize(srcFile.length()); out.putArchiveEntry(entry); IOUtils.copy(is, out); } out.closeArchiveEntry(); return destFile; } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(out); } } /** * 解压缩指定的源文件到目标目录 * * @param srcFile 源压缩文件 * @param destDir 目标解压缩目录 * @throws IOException 如果在解压缩过程中发生I/O错误 */ public static void doDecompress(File srcFile, File destDir) throws IOException { ZipArchiveInputStream is = null; try { is = new ZipArchiveInputStream(new BufferedInputStream(new FileInputStream(srcFile), bufferSize)); ZipArchiveEntry entry = null; while ((entry = is.getNextZipEntry()) != null) { if (entry.isDirectory()) { File directory = new File(destDir, entry.getName()); directory.mkdirs(); } else { OutputStream os = null; try { os = new BufferedOutputStream( new FileOutputStream(new File(destDir, entry.getName())), bufferSize); IOUtils.copy(is, os); } finally { IOUtils.closeQuietly(os); } } } } finally { IOUtils.closeQuietly(is); } } public static void main(String[] args) { try { ZipUtils.doCompressFiles(Arrays.asList(new File("/mnt/d/export").listFiles()), new File("/mnt/d/export.zip")); // List<File> files = new ArrayList<File>(); // files.add(new File("/pathto/abc.txt")); // files.add(new File("/pathto/xyz.txt")); // // // ZipUtils.doCompress(files, new File("/pathto/abc-test.zip")); // File doDecompressDir = new File("/pathto/abc-test1723"); // if (!doDecompressDir.exists()) { // doDecompressDir.mkdirs(); // } // ZipUtils.doDecompress(new File("/pathto/abc-test.zip"), doDecompressDir); } catch (IOException e) { e.printStackTrace(); } } }

XStream

XStream是一个Java对象和XML相互转换的工具,很好很强大

@Test public void function1() { List<Province> proList = getProvinceList(); /* * 创建XStream对象,调用toXML把集合转换成xml字符串 */ XStream xStream = new XStream(); String string = xStream.toXML(proList); System.out.println(string); /************* 将xml转为java对象 ******× ****/ String address_xml = "<ADDRESS Zipcode=\"710002\">\n" + " <Add>西安市雁塔路</Add>\n" + " </ADDRESS>"; // 同样使用上面的XStream对象将xml转换为Java对象 System.out.println(xStream.fromXML(address_xml).toString()); } public List<Province> getProvinceList() { Province p1 = new Province(); p1.setName("北京"); p1.addCity(new City("东城区", "dongchengqu")); p1.addCity(new City("昌平区", "changpingqu")); Province p2 = new Province(); p1.setName("山东省"); p1.addCity(new City("济南", "jinan")); p1.addCity(new City("青岛", "qingdao")); ArrayList<Province> provinceList = new ArrayList<Province>(); provinceList.add(p1); provinceList.add(p2); return provinceList; }

结果:

<list> <com.veeja.demo.Province> <name>北京</name> <cities> <com.veeja.demo.City> <name>东城区</name> <description>dongchengqu</description> </com.veeja.demo.City> <com.veeja.demo.City> <name>昌平区</name> <description>changpingqu</description> </com.veeja.demo.City> </cities> </com.veeja.demo.Province> <com.veeja.demo.Province> <name>山东省</name> <cities> <com.veeja.demo.City> <name>济南</name> <description>jinan</description> </com.veeja.demo.City> <com.veeja.demo.City> <name>青岛</name> <description>qingdao</description> </com.veeja.demo.City> </cities> </com.veeja.demo.Province> </list>

JSON

  • Jackson:SpringBoot默认是使用Jackson作为JSON数据格式处理的类库,Jackson在各方面都比较优秀。
  • FastJson是阿里巴巴公司提供的一个用Java语言编写的高性能功能完善的JSON库,该库涉及的最基本功能就是序列化和反序列化。Fastjson支持java bean的直接序列化,同时也支持集合、Map、日期、Enum和泛型等的序列化。你可以使用com.alibaba.fastjson.JSON这个类进行序列化和反序列化,常用的序列化操作都可以在JSON类上的静态方法直接完成。Fastjson采用独创的算法,将parse的速度提升到极致,号称超过所有Json库。而且,使用Fastjson解析时,除了需要使用Fastjson所提供的jar包外,再不需要额外的jar包,就能够直接跑在JDK上。

Jackson

pom.xml

<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.15.2</version> </dependency>

@JsonIgnoreProperties 注解说明

  • 作用: 该注解用于告诉 Jackson 在反序列化 JSON 数据时,忽略 JSON 中存在但 Java 类中不存在的属性
  • 使用场景: 当 JSON 数据包含比 Java 对象更多的字段时,避免出UnrecognizedPropertyException 异常。可以提高代码的健壮性,避免因为新增字段而导致解析失
@JsonIgnoreProperties(ignoreUnknown = true) public class MobileLocation { @JsonProperty("cardtype") private String cardType;

@JsonProperty 注解说明

指定 JSON 属性名与 Java 字段之间的映射关系。解决 JSON 字段名与 Java 属性名不一致的问题(如 snake_case 与 camelCase 的转换)

@JsonIgnore 注解说明

忽略特定字段的序列化/反序列化

@JsonIgnore private String password;

解析为Entity对象

import com.fasterxml.jackson.databind.ObjectMapper; // 创建ObjectMapper实例 ObjectMapper objectMapper = new ObjectMapper(); // JSON字符串 String jsonString = "{\"name\":\"张三\",\"age\":25}"; // 解析为自定义对象 Person person = objectMapper.readValue(jsonString, Person.class);

解析为Map对象

import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Map; ObjectMapper objectMapper = new ObjectMapper(); String jsonString = "{\"name\":\"张三\",\"age\":25}"; // 解析为Map Map<String, Object> map = objectMapper.readValue(jsonString, Map.class);

解析为JsonNode对象

  • 当JSON结构不确定或动态变化时,使用 JsonNode 可以灵活访问数据
  • 无需预先定义POJO类,直接解析并访问节点
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; ObjectMapper objectMapper = new ObjectMapper(); String jsonString = "{\"name\":\"张三\",\"age\":25}"; // 解析为JsonNode JsonNode jsonNode = objectMapper.readTree(jsonString); String name = jsonNode.get("name").asText(); int age = jsonNode.get("age").asInt(); if (jsonNode.has("name")) { String name = jsonNode.get("name").asText(); }

fastjson用法及常用方法总结

pom.xml

<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.28</version> </dependency>
  • put(String key, Object value)方法,在JSONObject对象中设置键值对在,在进行设值得时候,key是唯一的,如果用相同的key不断设值得时候,保留后面的值
    jsonObject.put(key,value);
  • Object get(String key) :根据key值获取JSONObject对象中对应的value值,获取到的值是Object类型,需要手动转化为需要的数据类型
    jsonObject.get(key);
  • int size():获取JSONObject对象中键值对的数量
    int size = jsonObject.size();
  • boolean isEmpty():判断该JSONObject对象是否为空
    boolean empty = jsonObject.isEmpty();
  • containsKey(Object key):判断是否有需要的key值
    boolean key = jsonObject.containsKey("key");
  • boolean containsValue(Object value):判断是否有需要的value值
    boolean value = jsonObject.containsValue("value");
  • StringgetString(String key) :如果JSONObject对象中的value是一个String字符串,既根据key获取对应的String字符串;
    String name = jsonObject.getString("name");
  • JSONObject getJSONObject(String key):如果JSONObjct对象中的value是一个JSONObject对象,即根据key获取对应的JSONObject对象;
    JSONObject key = jsonObject.getJSONObject("key");
  • JSONArray getJSONArray(String key) :如果JSONObject对象中的value是一个JSONObject数组,既根据key获取对应的JSONObject数组;
    String jsonString = "{\"array\":[{\"key1\":\"value1\"}, {\"key2\":\"value2\"}]}"; JSONObject jsonObject = JSON.parseObject(jsonString); JSONArray jsonArray = jsonObject.getJSONArray("array");
  • Object remove(Object key):根据key清除某一个键值对,并返回。
    Object key = jsonObject.remove("key");

由于JSONObject是一个map,它还具有map特有的两个方法:

  • Set keySet() :获取JSONObject中的key,并将其放入Set集合中
    Set<String> set = jsonObject.keySet();
  • Set<Map.Entry<String, Object>> entrySet():在循环遍历时使用,取得是键和值的映射关系,Entry就是Map接口中的内部接口
    Set<Map.Entry<String, Object>> entries = jsonObject.entrySet();
  • String字符串转换toJSONString() /toString():将JSONObject对象转换为json的字符串
    String string = jsonObject.toString(); String string = jsonObject.toJSONString();

1.通过原生生成json数据格式

import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; public class faskjson { public static void main(String[] args) { JSONObject dataJson = new JSONObject(); try { //添加 dataJson.put("name", "张三"); dataJson.put("age", 18.4); dataJson.put("birthday", "1900-20-03"); dataJson.put("majar", new String[]{"哈哈", "嘿嘿"}); dataJson.put("house", false); System.out.println(dataJson.toString()); //{"birthday":"1900-20-03","name":"张三","majar":["哈哈","嘿嘿"],"house":false,"age":18.4} } catch (JSONException e) { e.printStackTrace(); } } }

2.通过hashMap数据结构生成

HashMap<String, Object> map = new HashMap<>(); map.put("name", "张三"); map.put("age", 18.4); map.put("birthday", "1900-20-03"); map.put("majar", new String[] {"哈哈","嘿嘿"}); map.put("null", null); map.put("house", false); System.out.println(new JSONObject(map).toString()); //{"birthday":"1900-20-03","name":"张三","majar":["哈哈","嘿嘿"],"house":false,"age":18.4}

3.通过实体生成

Student student = new Student(); student.setId(1); student.setAge("20"); student.setName("张三"); //生成json格式 System.out.println(JSON.toJSON(student)); //对象转成string String stuString = JSONObject.toJSONString(student); System.out.println(stuString);

4.JSON字符串转换成JSON对象

String studentString = "{'id':1,\"age\":2,\"name\":\"zhang\"}"; //JSON字符串转换成JSON对象 JSONObject dataJson = JSONObject.parseObject(studentString); System.out.println(dataJson);

5.list对象转listJson

package net.demo.test; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import java.util.ArrayList; public class faskjson { public static void main(String[] args) { try { ArrayList<Student> studentList = new ArrayList<>(); Student student1 = new Student(); student1.setId(1); student1.setAge("20"); student1.setName("张三"); studentList.add(student1); Student student2 = new Student(); student2.setId(2); student2.setAge("25"); student2.setName("李四"); studentList.add(student2); //list转json字符串 String string = JSON.toJSON(studentList).toString(); System.out.println("jsonString:" + string); //json字符串转listJson格式 JSONArray jsonArray = JSONObject.parseArray(string); System.out.println("jsonArray:" + jsonArray); //jsonString:[{"name":"张三","id":1,"age":"20"},{"name":"李四","id":2,"age":"25"}] //jsonArray:[{"name":"张三","id":1,"age":"20"},{"name":"李四","id":2,"age":"25"}] } catch (JSONException e) { e.printStackTrace(); } } }

6.map转listJson

ArrayList<Object> list = new ArrayList<>(); String[] name = {"张三", "李四"}; for (int i = 0; i < name.length; i++) { HashMap map = new HashMap(); map.put("name", name[i]); list.add(map); } //list转json字符串 String string = JSON.toJSON(list).toString(); System.out.println("jsonString:" + string); //json字符串转listJson格式 JSONArray jsonArray = JSONObject.parseArray(string); System.out.println("jsonArray:" + jsonArray); //jsonString:[{"name":"张三"},{"name":"李四"}] //jsonArray:[{"name":"张三"},{"name":"李四"}] jsonArray.getJSONObject(0).getString("name");

Student.java

package net.demo.test; import lombok.Data; @Data public class Student { private Integer id; private String age; private String name; }

7.JSONObject,JSONArray的元素遍历

查看源代码JSONObject,JSONArray是JSON的两个子类。
JSONObject相当于Map<String, Object>,可以使用put方法给json对象添加元素
JSONArray相当于List<Object>

HashMap<String, Object> map = new HashMap<String, Object>(); map.put("key1", "One"); map.put("key2", "Two"); JSONObject j = new JSONObject(map); j.put("key3", "Three"); System.out.println(j.get("key1")); String retJson = "{\"msg\":\"success\",\"code\":\"000\",\"data\":{\"showNumber\":\"400050055522\",\"tel\":\"RDBVqQa2QBJW7Z2zLQW91Q==\"}}"; JSONObject responseJson = JSONObject.parseObject(retJson); JSONObject data = responseJson.getJSONObject("data"); String realPhone = data.getString("showNumber"); //将json中动态的key,value封装到JsonData JSONObject priceJsonData = JSONObject.parseObject(priceJson); JSONObject JsonData = new JSONObject(); Set<String> keySet = priceJsonData.keySet(); for (String key : keySet) { if (!StringUtils.isNumeric(key)) { JsonData.put(key, priceJsonData.get(key)); } } JSONArray jsonArray = JSONObject.parseArray(string); for (int i = 0; i < jsonArray.size(); i++) { System.out.println(jsonArray.get(i)); }

8.JSON对象–>Java对象

JSONObject.toJavaObject(JSON对象实例, Java对象.class);

public class JSON2JavaTest{ public static void main(String[] args) { Student stu = new Student("公众号编程大道", "m", 2); //先转成JSON对象 JSONObject jsonObject = (JSONObject) JSONObject.toJSON(stu); //JSON对象转换成Java对象 Student student = JSONObject.toJavaObject(jsonObject, Student.class); System.out.println("JSON对象转换成Java对象\n" + student);//Student{name='公众号编程大道', sex='m', age=2} } }

9.JSON字符串–>Java对象

public class JSON2JavaTest{ public static void main(String[] args) { String stuString = "{\"age\":2,\"name\":\"公众号编程大道\",\"sex\":\"m\"}"; //JSON字符串转换成Java对象 Student student1 = JSONObject.parseObject(stuString, Student.class); System.out.println("JSON字符串转换成Java对象\n" + student1);//Student{name='公众号编程大道', sex='m', age=2} }}

10.java对象转Map

public static HashMap<String, Object> objectToMap(Object object) { return JSONObject.parseObject(JSONObject.toJSONString(object), HashMap.class); }

Java中对json数字的兼容

判断是否为数字:

public static boolean isNumeric (String str) { //如果是数字,创建new BigDecimal()时肯定不会报错,那就可以直接返回true try { String bigdecimal = new BigDecimal(str).toString(); } catch (Exception e) { return false;//异常 说明包含非数字。 } return true; }

接着就可以利用判断结果进行转换了

map = new Gson().fromJson(String.valueOf(list.get(i)),HashMap.class); String oldValue = map.get("value").toString(); if (isNumeric(oldValue)){ BigDecimal value = new BigDecimal(oldValue); restful.query.put(map.get("name").toString(),value); }else { restful.query.put(map.get("name").toString(),map.get("value")); } BigDecimal value = jsonobject.getBigDecimal(key); //比如保留六位小数,四舍五入 value.setScale(4, RoundingMode.HALF_UP);

Json对象Key不忽略null值

JSONObject.toJSONString(entity, SerializerFeature.WriteMapNullValue)

JSONObject排序不乱

JSONObject jsonObject1 = new JSONObject(); //无序的HashMap #方法1 JSONObject jsonObject2 = new JSONObject(true); //有序设置方法一,LinkedHashMap #方法2 // 参数2:Feature.OrderedField用来保证解析顺序正确 JSONObject obj = JSONObject.parseObject(jsonStr, Feature.OrderedField);

JSONObject判断类型

if (jsonObject instanceof JSONArray)

JSON排除指定字段

import com.alibaba.fastjson.JSON; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Map字段过滤工具类 提供将对象转换为Map并排除指定字段的功能 */ public class MapFieldFilter { /** * 将对象转换为Map,并排除指定字段 * * @param obj 需要转换的对象 * @param excludeFields 需要排除的字段列表 * @return 转换后的Map,不包含指定字段 */ public static <T> Map<String, Object> toMapWithExcludedFields(T obj, List<String> excludeFields) { // 将对象转换为JSON字符串,再解析为Map Map<String, Object> map = JSON.parseObject(JSON.toJSONString(obj), Map.class); // 遍历需要排除的字段列表,从Map中移除这些字段 for (String field : excludeFields) { map.remove(field); } return map; } /** * 从对象列表中过滤掉指定字段 * * @param list 对象列表 * @param excludeFields 需要排除的字段列表 * @return 过滤后的Map列表,每个Map都不包含指定字段 */ public static <T> List<Map<String, Object>> filterFieldsFromList(List<T> list, List<String> excludeFields) { // 使用流处理,对列表中的每个对象应用字段过滤 return list.stream() .map(obj -> toMapWithExcludedFields(obj, excludeFields)) .collect(Collectors.toList()); } public static void main(String[] args) { // 创建List /*List<User> userList = Arrays.asList( new User("Alice", 30, "alice@example.com", true), new User("Bob", 25, "bob@example.com", false) ); List<String> excludeFields = Arrays.asList("age", "email"); List<Map<String, Object>> result = MapFieldFilter.filterFieldsFromList(userList, excludeFields); User user = new User("Alice", 30, "alice@example.com", true); Map<String, Object> result = MapFieldFilter.toMapWithExcludedFields(user, excludeFields); assertEquals(30, result.get("age"));*/ } }

FastJson2全局配置

Fastjson2 默认读取时不会自动将下划线命名转换为驼峰命名

import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONReader; import com.alibaba.fastjson2.JSONWriter; import com.alibaba.fastjson2.filter.NameFilter; import com.alibaba.fastjson2.support.config.FastJsonConfig; import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; /** * Fastjson2 全局配置 - 完全兼容 Fastjson 1.1 特性 * <p> * 核心功能: * 1. 启用下划线 ↔ 驼峰自动转换(SupportSmartMatch) * 2. 优化驼峰转下划线算法,支持连续大写字母(如 XMLParser → xml_parser) * 3. 配置日期时间格式化(LocalDateTime/LocalDate/LocalTime) * 4. 兼容 Fastjson 1.1 的默认行为(null 值处理、循环引用、单引号、无引号字段名等) * 5. 提供静态工具方法供手动调用 * </p> * <p> * 特性对照: * Fastjson 1.1 SerializerFeature → Fastjson2 JSONWriter.Feature * Fastjson 1.1 Feature → Fastjson2 JSONReader.Feature * </p> * <p> * Fastjson2 版本要求: >= 2.0.12 (支持 AllowSingleQuotes 和 AllowUnQuotedFieldNames) * </p> * * @author hudy * @since 2026-05-21 */ @Configuration public class FastJson2Config { // ==================== 日期格式配置 ==================== private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; // ==================== 驼峰转下划线 Filter ==================== /** * 驼峰转下划线 NameFilter(序列化时:camelCase → snake_case) */ private static final NameFilter CAMEL_TO_SNAKE_FILTER = (object, name, value) -> camelToSnake(name); /** * 驼峰转下划线工具方法 * <p> * 支持处理连续大写字母,例如: * - "XMLParser" → "xml_parser"(正确) * - "userID" → "user_id"(正确,而非 "user_i_d") * - "userName" → "user_name"(正确) * - "parseXMLDoc" → "parse_xml_doc"(正确) * </p> */ private static String camelToSnake(String str) { if (str == null || str.isEmpty()) { return str; } StringBuilder sb = new StringBuilder(); int len = str.length(); for (int i = 0; i < len; i++) { char c = str.charAt(i); if (Character.isUpperCase(c)) { // 处理连续大写字母的情况: // 1. 如果前面是小写字母,则添加下划线(如 "userName" → "user_name") // 2. 如果后面是小写字母且当前不是最后一个字符,则添加下划线(如 "XMLParser" → "xml_parser") if (i > 0 && Character.isLowerCase(str.charAt(i - 1))) { sb.append('_'); } else if (i > 0 && i < len - 1 && Character.isUpperCase(c) && Character.isLowerCase(str.charAt(i + 1))) { sb.append('_'); } sb.append(Character.toLowerCase(c)); } else { sb.append(c); } } return sb.toString(); } // ==================== Spring MVC 消息转换器 ==================== /** * 配置 FastJsonHttpMessageConverter * <p> * 用于 Spring MVC 的 HTTP 请求/响应自动序列化/反序列化 * 兼容 Fastjson 1.1 的默认行为 * </p> */ @Bean public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); converter.setDefaultCharset(StandardCharsets.UTF_8); // 设置支持的 MediaType List<MediaType> mediaTypes = new ArrayList<>(); mediaTypes.add(MediaType.APPLICATION_JSON); mediaTypes.add(new MediaType("application", "*+json")); converter.setSupportedMediaTypes(mediaTypes); FastJsonConfig config = new FastJsonConfig(); // ---------- 日期格式配置 ---------- config.setDateFormat(DATE_TIME_FORMAT); // ---------- 写入特性(序列化)兼容 Fastjson 1.1 SerializerFeature ---------- config.setWriterFeatures( // 【WriteMapNullValue】写入 null 值字段(Fastjson 1.1 常用) JSONWriter.Feature.WriteMapNullValue, // 【WriteNullListAsEmpty】List 为 null 时输出 [] JSONWriter.Feature.WriteNullListAsEmpty, // 枚举使用 name() 序列化 JSONWriter.Feature.WriteEnumsUsingName ); // ---------- 读取特性(反序列化)兼容 Fastjson 1.1 Feature ---------- config.setReaderFeatures( // 【UseBigDecimalForDoubles】使用 BigDecimal 处理浮点数(避免精度丢失) JSONReader.Feature.UseBigDecimalForDoubles, // 【SupportArrayToBean】支持数组转 Bean JSONReader.Feature.SupportArrayToBean, // 【关键】支持下划线转驼峰(snake_case → camelCase) JSONReader.Feature.SupportSmartMatch, // 【安全】禁用 AutoType,防止反序列化漏洞 //JSONReader.Feature.DisableAutoType, // 【安全】忽略不存在的字段 JSONReader.Feature.IgnoreSetNullValue, // 【兼容】允许单引号包裹字段名和字符串值(Fastjson 1.1 默认开启) //JSONReader.Feature.AllowSingleQuotes, // 【兼容】允许不带双引号的字段名(Fastjson 1.1 默认开启) JSONReader.Feature.AllowUnQuotedFieldNames ); converter.setFastJsonConfig(config); return converter; } // ==================== 全局静态配置(用于手动调用 JSON API)==================== /** * 获取兼容 Fastjson 1.1 的 Reader 特性数组 * <p> * 使用方式: * <pre> * // Fastjson 1.1 写法 * User user = JSON.parseObject(json, User.class, Feature.AllowSingleQuotes); * * // Fastjson2 写法 * User user = JSON.parseObject(json, User.class, FastJson2Config.getReaderFeatures()); * </pre> */ public static JSONReader.Feature[] getReaderFeatures() { return new JSONReader.Feature[]{ // 【UseBigDecimalForDoubles】使用 BigDecimal 处理浮点数(避免精度丢失) JSONReader.Feature.UseBigDecimalForDoubles, // 【SupportArrayToBean】支持数组转 Bean JSONReader.Feature.SupportArrayToBean, // 【关键】支持下划线转驼峰(snake_case → camelCase) JSONReader.Feature.SupportSmartMatch, // 【安全】禁用 AutoType,防止反序列化漏洞 //JSONReader.Feature.DisableAutoType, // 【安全】忽略不存在的字段 JSONReader.Feature.IgnoreSetNullValue, // 【兼容】允许单引号包裹字段名和字符串值(Fastjson 1.1 默认开启) //JSONReader.Feature.AllowSingleQuotes, // 【兼容】允许不带双引号的字段名(Fastjson 1.1 默认开启) JSONReader.Feature.AllowUnQuotedFieldNames }; } /** * 获取兼容 Fastjson 1.1 的 Writer 特性数组 * <p> * 使用方式: * <pre> * // Fastjson 1.1 写法 * String json = JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue); * * // Fastjson2 写法 * String json = JSON.toJSONString(obj, FastJson2Config.getWriterFeatures()); * </pre> */ public static JSONWriter.Feature[] getWriterFeatures() { return new JSONWriter.Feature[]{ JSONWriter.Feature.WriteMapNullValue, JSONWriter.Feature.WriteNullListAsEmpty, JSONWriter.Feature.WriteEnumsUsingName }; } /** * 手动序列化时应用驼峰转下划线 * <p> * 使用方式: * <pre> * String json = JSON.toJSONString(obj, FastJson2Config.getCamelToSnakeFilter(), FastJson2Config.getWriterFeatures()); * </pre> */ public static NameFilter getCamelToSnakeFilter() { return CAMEL_TO_SNAKE_FILTER; } // ==================== 兼容 Fastjson 1.1 的静态工具方法 ==================== /** * 兼容 Fastjson 1.1 的 JSON.parseObject 写法 * <p> * 自动应用 SupportSmartMatch 等特性,支持下划线 ↔ 驼峰转换 * </p> * * @param text JSON 字符串 * @param clazz 目标类型 * @return 解析后的对象 */ public static <T> T parseObject(String text, Class<T> clazz) { return JSON.parseObject(text, clazz, getReaderFeatures()); } /** * 兼容 Fastjson 1.1 的 JSON.toJSONString 写法 * <p> * 自动应用驼峰转下划线 Filter 和 Writer Features * </p> * * @param obj 待序列化对象 * @return JSON 字符串(字段名为下划线格式) */ public static String toJSONString(Object obj) { return JSON.toJSONString(obj, getCamelToSnakeFilter(), getWriterFeatures()); } /** * 不应用驼峰转下划线的 toJSONString * <p> * 用于需要保持原始字段名的场景 * </p> * * @param obj 待序列化对象 * @return JSON 字符串(字段名保持原样) */ public static String toJSONStringWithoutSnake(Object obj) { return JSON.toJSONString(obj, getWriterFeatures()); } }

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询