package com.xxx.framework.common.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.ClassPathResource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
public class JsonUtil {
/**
* 单位缩进字符串。
*/
private static String SPACE = " ";
public static <T extends Collection<E>, E> T fromJson4Collection(String jsonStr, Class<T> collectionClass, Class<E> clazz) throws IOException {
ObjectMapper om = new ObjectMapper();
JavaType javaType = om.getTypeFactory().constructCollectionType(collectionClass, clazz);
return (T) om.readValue(jsonStr, javaType);
}
public static String toJson4Collection(Collection pojoColl) throws IOException {
return toJson(pojoColl);
}
public static String toJson(Object pojo) throws IOException {
JsonFactory jf = new JsonFactory();
ObjectMapper om = new ObjectMapper();
StringWriter sw = new StringWriter();
JsonGenerator jg = jf.createGenerator(sw);
jg.useDefaultPrettyPrinter();
om.writeValue(jg, pojo);
return sw.toString();
}
/**
* 读取简单的JSON文件
* @param path JSON文件的路径
* @return json文件转换的map
* @throws IOException
*/
public static HashMap readSimpleJsonObj(String path) throws FileNotFoundException {
ClassPathResource resource = new ClassPathResource(path);
if (resource.exists()) {
try {
return JSON.parseObject(
resource.getInputStream(),
// 编码
StandardCharsets.UTF_8,
// 返回Map
HashMap.class,
// 自动关闭流
Feature.AutoCloseSource,
// 允许注释
Feature.AllowComment,
// 允许单引号
Feature.AllowSingleQuotes,
// 使用 Big decimal
Feature.UseBigDecimal
);
} catch (Exception e) {
return new HashMap();
}
} else {
throw new FileNotFoundException("Json file not find!");
}
}
/**
* 读取JSON文件
* @param path 文件路径
* @param clazz 转换对象的类型
* @param <T> 接收的对象
* @return
* @throws IOException
*/
public static <T> List<T> readJsonArray(String path, Class clazz) throws IOException {
ClassPathResource resource = new ClassPathResource(path);
if (resource.exists()) {
try {
String result = JSONObject.parseObject(
resource.getInputStream(),
String.class,
// 自动关闭流
Feature.AutoCloseSource,
// 允许注释
Feature.AllowComment,
// 允许单引号
Feature.AllowSingleQuotes,
// 使用 Big decimal
Feature.UseBigDecimal
);
return JSONArray.parseArray(result, clazz);
} catch (Exception e) {
return new ArrayList<T>();
}
} else {
throw new FileNotFoundException("Json file not find!");
}
}
/**
* 读取JSON文件
* @param path JSON文件的路径
* @return json文件转换的对象
* @throws IOException
*/
public static <T> T readJsonObj(String path, Class clazz) throws FileNotFoundException {
ClassPathResource resource = new ClassPathResource(path);
if (resource.exists()) {
try {
return JSON.parseObject(
resource.getInputStream(),
// 编码
StandardCharsets.UTF_8,
// 返回Map
clazz,
// 自动关闭流
Feature.AutoCloseSource,
// 允许注释
Feature.AllowComment,
// 允许单引号
Feature.AllowSingleQuotes,
// 使用 Big decimal
Feature.UseBigDecimal
);
} catch (Exception e) {
Instance<T> tInstance = new Instance<>(clazz);
return tInstance.type;
}
} else {
throw new FileNotFoundException("Json file not find!");
}
}
/**
* 将内容写入json文件
* @param filePath
* @param sets
* @return
*/
public static void writeJsonFile(String filePath, String sets) throws Exception {
FileWriter fw;
try {
File jsonFile = new File(filePath);
if (jsonFile.exists())
jsonFile.delete();
jsonFile.createNewFile();
fw = new FileWriter(filePath);
PrintWriter out = new PrintWriter(fw);
out.write(sets);
out.println();
fw.close();
out.close();
} catch (IOException e) {
throw new Exception(e);
}
}
/**
* 返回格式化JSON字符串。
*
* @param json 未格式化的JSON字符串。
* @return 格式化的JSON字符串。
*/
public static String formatJson(String json) {
StringBuffer result = new StringBuffer();
int length = json.length();
int number = 0;
char key = 0;
// 遍历输入字符串。
for (int i = 0; i < length; i++) {
// 1、获取当前字符。
key = json.charAt(i);
// 2、如果当前字符是前方括号、前花括号做如下处理:
if ((key == '[') || (key == '{')) {
// (1)如果前面还有字符,并且字符为“:”,打印:换行和缩进字符字符串。
if ((i - 1 > 0) && (json.charAt(i - 1) == ':')) {
result.append('\n');
result.append(indent(number));
}
// (2)打印:当前字符。
result.append(key);
// (3)前方括号、前花括号,的后面必须换行。打印:换行。
result.append('\n');
// (4)每出现一次前方括号、前花括号;缩进次数增加一次。打印:新行缩进。
number++;
result.append(indent(number));
// (5)进行下一次循环。
continue;
}
// 3、如果当前字符是后方括号、后花括号做如下处理:
if ((key == ']') || (key == '}')) {
// (1)后方括号、后花括号,的前面必须换行。打印:换行。
result.append('\n');
// (2)每出现一次后方括号、后花括号;缩进次数减少一次。打印:缩进。
number--;
result.append(indent(number));
// (3)打印:当前字符。
result.append(key);
// (4)如果当前字符后面还有字符,并且字符不为“,”,打印:换行。
if (((i + 1) < length) && (json.charAt(i + 1) != ',')) {
result.append('\n');
}
// (5)继续下一次循环。
continue;
}
// 4、如果当前字符是逗号。逗号后面换行,并缩进,不改变缩进次数。
if ((key == ',')) {
result.append(key);
result.append('\n');
result.append(indent(number));
continue;
}
// 5、打印:当前字符。
result.append(key);
}
return result.toString();
}
/**
* 返回指定次数的缩进字符串。每一次缩进三个空格,即SPACE。
*
* @param number 缩进次数。
* @return 指定缩进次数的字符串。
*/
private static String indent(int number) {
StringBuffer result = new StringBuffer();
for (int i = 0; i < number; i++) {
result.append(SPACE);
}
return result.toString();
}
static class Instance<T> {
T type;
private Instance(Class<T> clz) {
try {
type = clz.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Json简单操作的工具类(写入json文件,读取json文件,json文件格式处理)
最新推荐文章于 2024-05-26 09:57:41 发布