读取zip文件作为资源会导致奇数编码更改

时间:2018-02-09 17:59:53

标签: java json intellij-idea character-encoding zip

我有一个(非常大的)JSON集合,必须作为资源作为JAR文件的一部分进行分发。由于这个数字很大,以编程方式对所有名称进行硬编码是不可行的,因此我将它们全部存储在一个zip文件中,在那里我可以轻松地遍历它们。

相关代码如下:

let greatest_value = *vector.iter().max().unwrap();

现在......当我在IDE中运行应用程序时,这个代码工作正常(即,无论IntelliJ如何处理POM中指示的src / main / resources目录),但只要我尝试运行这个代码作为打包JAR的一部分,我收到以下错误:

 ZipInputStream zis = new ZipInputStream(SchemaReader.class.getResourceAsStream("/org/hl7/fhir/schema/dstu3.zip"));
    ZipEntry entry;
    try {
        while ((entry = zis.getNextEntry()) != null) {
            String name = entry.getName();
            if (name.equalsIgnoreCase("fhir.schema.json") || name.equalsIgnoreCase("ResourceList.schema.json")) {
                continue; // Skip over the root definition to prevent duplicates
            }
            String definition = IOUtils.toString(zis);
            zis.closeEntry();
            JsonObject root = new JsonParser().parse(definition).getAsJsonObject();
            JsonObject definitionMap = root.getAsJsonObject("definitions");
            for (Map.Entry<String, JsonElement> e : definitionMap.entrySet()) {
                definitions.put(name + "#/definitions/" + e.getKey(), root);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

这与行

有关
Caused by: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 5 path $

我在运行.jar时使用IntelliJ的调试器进一步调查,发现由于某种原因,提取的JSON在前面编码了奇数字符:

JsonObject root = new JsonParser().parse(definition).getAsJsonObject();

JSON的其余部分显示正常,但我没有详尽地检查这个

这导致我怀疑编码错误,因此我更改了IOUtils#toString调用以添加各种可能的编码。

不幸的是,到目前为止我没有成功,有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我怀疑你得到Byte Order Mark。尝试使用Apache Commons IO BOMInputStream来包装InputStream。请注意&#34;基本&#34;构造函数只删除ByteOrderMark.UTF_8 BOM,这在大多数情况下都没问题。但如果没有,请尝试使用构造函数,让您指定其他BOMS并将其全部添加(或者进行实验直到找到正确的BOMS)