【问题标题】:Reading file json and convert to string and replace chars in java8读取文件json并转换为字符串并替换java8中的字符
【发布时间】:2021-11-04 08:04:37
【问题描述】:

如何读取文件并从 json 转换为字符串? 例子: 我有文件 numbers.json [ "23423423", "234234234", “53453453” ]

我想拥有: 字符串数字 = "'23423423', '234234234', '53453453'";

【问题讨论】:

    标签: java json char replaceall file.readalllines


    【解决方案1】:

    这是代码,没有使用任何类型的库,(假设你只有像你一样的单个数组形式的 json。

    String json = "[\"23423423\", \"234234234\", \"53453453\" ]"
    String formattedJson = json.replace("[", "").replace("]", "").replace("\"", "").replace(" ", "");
    String [] nums = formattedJson.split(",");
    

    您的数字将出现在 nums[] 数组中。

    【讨论】:

    • 正确的做法是先解码JSON再访问对象的内容;不要破坏字符串表示,这总是会在将来的某个时候导致问题。
    【解决方案2】:
    Path path = Paths.get(".../.../numbers.json");
        List<String> listString= Files.readAllLines(path);
        String result = listString.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(""));
    
        result = result.replace("\"", "\'");
        result = result.replace("[", "");
        result = result.replace("]", "");
        return result;
    

    这就是我编写代码的方式,但我知道,它看起来很糟糕..

    【讨论】:

    • 你可以看到这个答案link
    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    相关资源
    最近更新 更多