我在代码中硬编码了这个 JSON 字符串。
String json = "{\n" +
" \"id\": 1,\n" +
" \"name\": \"Headphones\",\n" +
" \"price\": 1250.0,\n" +
" \"tags\": [\"home\", \"green\"]\n" +
"}\n"
;
我想将其移至资源文件夹并从那里读取它,
我怎样才能在JAVA中做到这一点?
根据我的经验,这是从类路径读取文件的最可靠的模式。[1]
Thread.currentThread().getContextClassLoader().getResourceAsStream("YourJsonFile")
它给你一个InputStream
[2] 可以传递给大多数 JSON 库。[3]
try(InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream("YourJsonFile")){
//pass InputStream to JSON-Library, e.g. using Jackson
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readValue(in, JsonNode.class);
String jsonString = mapper.writeValueAsString(jsonNode);
System.out.println(jsonString);
}
catch(Exception e){
throw new RuntimeException(e);
}
[1] 将文件作为输入流加载的不同方法 https://stackoverflow.com/questions/676250/different-ways-of-loading-a-file-as-an-inputstream
[2] Try With Resources 与 Try-Catch https://stackoverflow.com/questions/26516020/try-with-resources-vs-try-catch
[3] https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core
Hint:不要尝试在内部使用此方法parallelStream
或类似的。这将导致异常。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)