Springboot上传.Json文件参数,转成json数据
一:在外面的日常开发中会使用到.json文件进行传参,因为有可能参数的数据很大
如下:
像这种.json文件的传输,需要我们解析出来,我这里用到的是MultipartFile表单方式传输
二:解析如下,解析到字符串,也可以去除换行符
三:下面就是转json数据了,首先转成file再转json
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
/**
* @author lrx
* @description: TODO 读取json文件工具类
* @date 2021/7/19 10:42
*/
public class ReadJsonFileUtils {
//读取json文件
public static String readJsonFile(MultipartFile fileName) throws Exception {
File file = multipartFileToFile(fileName);
String jsonStr = "";
try {
FileReader fileReader = new FileReader(file);
Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* MultipartFile 转 File
*
* @param file
* @throws Exception
*/
public static File multipartFileToFile(MultipartFile file) throws Exception {
File toFile = null;
if (file.equals("") || file.getSize() <= 0) {
file = null;
} else {
InputStream ins = null;
ins = file.getInputStream();
toFile = new File(file.getOriginalFilename());
inputStreamToFile(ins, toFile);
ins.close();
}
return toFile;
}
//获取流文件
private static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}