Java 导入导出JSON文件

这是一个Java工具类,用于处理JSON文件的读取和导出。它支持从MultipartFile和File对象读取JSON或TXT文件,并检查文件格式是否正确。同时,提供了一个方法用于将对象转换为JSON格式并保存到指定路径的文件中,支持文件下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.test.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.test.commons.rest.RestErrorEnum;
import com.test.commons.rest.RestException;
import org.apache.commons.io.FileUtils;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * Json export or import.
 *
 * @author levi
 **/
@PropertySource(value = "classpath:application.yml")
public class JsonUtil {

    public static final String TEMP_PATH = "template-temp";

    /**
     * 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;
    }

    public static Map<String, String> readJson(File multipartFile) {
        Map<String, String> result = new HashMap<>();
        try {
            String fileName = multipartFile.getName();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //MultipartFile to string
            //File file = new File("/" + fileName);
            //FileUtils.copyInputStreamToFile(new FileInputStream(file), file);
            String jsonString = FileUtils.readFileToString(multipartFile, "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 File exportJson(HttpServletResponse response, Object obj, String fileName, String uploadPath) {
        try {
            String jsonString = JSON.toJSONString(obj,
                    SerializerFeature.PrettyFormat,
                    SerializerFeature.WriteMapNullValue,
                    SerializerFeature.WriteDateUseDateFormat);

            //String fullPath = "/" + fileName;
            File path = new File(uploadPath);
            if (!path.exists()) {
                path.mkdirs();
            }
            String fullPath = uploadPath + "/" + 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();

            return file;
        } catch (Exception e) {
            throw new RestException(RestErrorEnum.PARAMETERS_ERROR, "导出模板JSON文件失败");
        }
    }

}


<think>嗯,用户想知道如何通过Java接口导出JSON格式文件,并且希望看到使用接口的示例。首先,我需要回想一下Java中处理JSON的常用库,比如Jackson或者Gson。用户提到要使用接口,所以可能需要定义一个导出接口,然后实现这个接口来处理JSON导出。 首先,得先定义一个导出接口,可能包含导出方法,接收数据和输出流。然后,实现这个接口的JSON导出类。需要处理如何将数据转换为JSON格式,并写入到输出流中。 然后,考虑代码结构。接口可能有一个export方法,接受数据和输出流。JSON实现类里,使用ObjectMapper来写入数据到输出流。同时,需要处理异常,比如IOException,可能需要关闭资源或者抛出异常。 还要注意示例的正确性,比如使用try-with-resources来自动关闭文件流,确保资源释放。可能还需要提到如何调用这个接口,比如在业务层创建导出器实例,调用export方法,并指定文件路径。 另外,用户提供的引用中提到了导出不同格式文件,比如CSV、Excel、PDF,以及ZIP压缩包。可能需要参考这些引用中的接口设计方式,保持一致性。例如,引用[1]中的导出接口定义,引用[2]中的文件操作类导入,引用[4]中的ZIP处理方式,虽然JSON不同,但结构上可能有相似之处。 还要检查是否需要处理返回值,引用[3]提到了FileOutputStream的getChannel方法,但用户的问题主要是导出JSON,所以可能不需要涉及返回值,但需要确保输出流正确关闭。 最后,生成相关问题时要考虑用户可能进一步的需求,比如性能优化、如何处理复杂数据结构,或者与其他格式导出的对比。</think>以下是通过Java接口导出JSON格式文件的实现步骤和示例代码: ### 一、接口定义 首先定义统一的文件导出接口,支持多种格式扩展: ```java public interface FileExporter { void export(Object data, OutputStream outputStream) throws IOException; } ``` ### 二、JSON实现类 使用Jackson库实现JSON导出(需添加依赖:`com.fasterxml.jackson.core:jackson-databind`): ```java public class JsonExporter implements FileExporter { private final ObjectMapper objectMapper = new ObjectMapper(); @Override public void export(Object data, OutputStream outputStream) throws IOException { try (outputStream) { objectMapper.writeValue(outputStream, data); outputStream.flush(); } } } ``` ### 三、使用示例 ```java public class ExportService { public void exportUserData(List<User> users, String filePath) { FileExporter exporter = new JsonExporter(); try (FileOutputStream fos = new FileOutputStream(filePath)) { exporter.export(users, fos); System.out.println("JSON文件导出成功:" + filePath); } catch (IOException e) { System.err.println("导出失败:" + e.getMessage()); } } } ``` ### 四、技术要点 1. **依赖管理**:需要Jackson库支持JSON序列化 2. **异常处理**:使用try-with-resources确保资源释放[^3] 3. **数据格式**:支持任意可序列化的Java对象 4. **扩展性**:符合开闭原则,新增格式只需实现接口[^1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值