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上。
JSONObject可以很方便的转换成字符串,也可以很方便的把其他对象转换成JSONObject对象。pom
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
JSONObject用法及常用方法总结
- 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");
- String getString(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"));*/
}
}