You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java8如何读取JSON文件转字符串并替换字符得到指定格式结果

Java8 读取JSON数组转指定格式字符串实现方案

方案1:使用Jackson JSON库(推荐)

适合大部分场景,兼容JSON结构变动,是Java生态通用的JSON处理方式。

前置依赖(Maven为例)

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>

完整实现代码

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

public class JsonParseDemo {
    public static void main(String[] args) throws IOException {
        // 初始化Jackson解析器
        ObjectMapper objectMapper = new ObjectMapper();
        // 读取JSON文件并解析为字符串列表
        List<String> numberList = objectMapper.readValue(
                new File("numbers.json"),
                new TypeReference<List<String>>() {}
        );
        // 拼接为指定格式的字符串
        String numbers = numberList.stream()
                .map(num -> "'" + num + "'")
                .collect(Collectors.joining(", "));
        
        // 输出结果:'23423423', '234234234', '53453453'
        System.out.println(numbers);
    }
}

方案2:纯JDK实现(无需第三方依赖)

仅适合当前固定结构的简单JSON场景,直接读取文件内容做字符替换即可:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class PureJdkImpl {
    public static void main(String[] args) throws IOException {
        // 读取JSON文件全量内容为字符串
        String content = new String(Files.readAllBytes(Paths.get("numbers.json")));
        // 按规则替换字符:去掉方括号、换行、多余空格,把双引号替换为单引号
        String numbers = content.replaceAll("[\\[\\]\\n\\s\"]", "")
                .replace(",", "', '");
        // 补全首尾单引号
        numbers = "'" + numbers + "'";
        
        // 输出结果:'23423423', '234234234', '53453453'
        System.out.println(numbers);
    }
}

内容的提问来源于stack exchange,提问作者svz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 21:54:03