Java 使用Json导入数据、数据导出Json文件
简介
通过json格式的文件导入一条数据记录,或导出一条记录的Json内容。
Maven
只列出主要依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.70</version>
</dependency>
JsonUtil 工具类
package com.levi.uitls;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
/**
* Json export or import.
*
* @author levi
* @version 1.0
**/
public class JsonUtil {
/**
* readJson.
* @param multipartFile multipartFile
* @return obj
*/
public static Map<String, String> readJson(MultipartFile multipartFile) {
Map<String, String> result = new HashMap<>();
try {
String fileName = multipartFile.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//MultipartFile to string
File file = new File("/" + fileName);
FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
String jsonString = FileUtils.readFileToString(file, "UTF-8");
if (".json".equals(suffixName) || ".txt".equals(suffixName)) {
result.put("result", jsonString);
result.put("code", "200");
result.put("message", "上传成功!");
} else {
result.put("result", "");
result.put("code", "500");
result.put("message", "请上传正确格式的.json或.txt文件!");
}
} catch (Exception e) {
e.printStackTrace();
result.put("result", "");
result.put("code", "500");
result.put("message", e.getMessage());
}
return result;
}
/**
* exportJson.
* @param response response
* @param obj obj
* @param fileName fileName
*/
public static void exportJson(HttpServletResponse response, Object obj, String fileName){
try {
String jsonString = JSON.toJSONString(obj,
SerializerFeature.PrettyFormat,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteDateUseDateFormat);
String fullPath = "/" + fileName;
File file = new File(fullPath);
Writer write = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
write.write(jsonString);
write.flush();
write.close();
FileInputStream fis = new FileInputStream(file);
// force-download
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
response.setCharacterEncoding("utf-8");
OutputStream os = response.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len = fis.read(buf)) != -1) {
os.write(buf, 0, len);
}
fis.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
接口层使用
@RestController
@RequestMapping("/api/test")
public class TestController {
@Autowired
private IUserService userService;
/**
* 使用Json导出
* @param response response
* @param id id
*/
@GetMapping(value = "/export")
public void exportJson(HttpServletResponse response,
@RequestParam(name="id",required=false)String id,
@RequestParam(name="name",required=false)String name) {
final User user = userService.getById(id); //根据具体业务定义
if (null == user) {
throw new AppException("未找到实体!");
}
//导出
JsonUtil.exportJson(response, user, name + "-" + UUIDUitl.getUUID8() + ".json");
}
/**
* 使用Json导入
* @param multipartFile multipartFile
* @return Object
*/
@PostMapping(value = "/import")
public Object importJson(MultipartFile multipartFile) {
final Map<String, String> result = JsonUtil.readJson(multipartFile);
if ("200".equals(result.get("code"))) {
final String jsonString = result.get("result");
final User user = JSON.parseObject(jsonString, User.class);
//导入
userService.save(user);
}
return result;
}
}