从资源中读取json文件,在JAVA中转换为json字符串

6ovsh4lw  于 2023-02-26  发布在  Java
关注(0)|答案(6)|浏览(136)

我在代码中硬编码了这个JSON字符串。

String json = "{\n" +
              "    \"id\": 1,\n" +
              "    \"name\": \"Headphones\",\n" +
              "    \"price\": 1250.0,\n" +
              "    \"tags\": [\"home\", \"green\"]\n" +
              "}\n"
;

我想把它移动到资源文件夹并从那里读取它,我怎么能在JAVA中做到这一点?

f4t66c6m

f4t66c6m1#

根据我的经验,这是从类路径读取文件最可靠的模式。[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][Different ways of loading a file as an InputStream](https://stackoverflow.com/questions/676250/different-ways-of-loading-a-file-as-an-inputstream)
[2][Try With Resources vs 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)

nnvyjq4y

nnvyjq4y2#

将json移动到resources文件夹中的文件someName.json

{
  id: 1,
  name: "Headphones",
  price: 1250.0,
  tags: [
    "home",
    "green"
  ]
}

像这样读取json文件

File file = new File(
        this.getClass().getClassLoader().getResource("someName.json").getFile()
    );

此外,您可以使用file对象,无论您想使用。您可以使用您最喜爱的json库转换为json对象。
例如,使用Jackson可以

ObjectMapper mapper = new ObjectMapper();
SomeClass someClassObj = mapper.readValue(file, SomeClass.class);
pgccezyw

pgccezyw3#

有许多可能的方法可以做到这一点:

完整读取文件*(仅适用于较小的文件)*

public static String readFileFromResources(String filename) throws URISyntaxException, IOException {
    URL resource = YourClass.class.getClassLoader().getResource(filename);  
    byte[] bytes = Files.readAllBytes(Paths.get(resource.toURI()));  
    return new String(bytes);  
}

逐行读入文件*(也适用于较大的文件)*

private static String readFileFromResources(String fileName) throws IOException {
    URL resource = YourClass.class.getClassLoader().getResource(fileName);

    if (resource == null)
        throw new IllegalArgumentException("file is not found!");

    StringBuilder fileContent = new StringBuilder();

    BufferedReader bufferedReader = null;
    try {
        bufferedReader = new BufferedReader(new FileReader(new File(resource.getFile())));

        String line;
        while ((line = bufferedReader.readLine()) != null) {
            fileContent.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return fileContent.toString();
}

最方便的方法是使用apache-commons.io

private static String readFileFromResources(String fileName) throws IOException {
    return IOUtils.resourceToString(fileName, StandardCharsets.UTF_8);
}
ct2axkht

ct2axkht4#

从资源中传递您的文件路径:
示例:如果您的resources -> folder_1 -> filename.json Then传入

String json = getResource("folder_1/filename.json");
public String getResource(String resource) {
        StringBuilder json = new StringBuilder();
        try {
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream(resource)),
                            StandardCharsets.UTF_8));
            String str;
            while ((str = in.readLine()) != null)
                json.append(str);
            in.close();
        } catch (IOException e) {
            throw new RuntimeException("Caught exception reading resource " + resource, e);
        }
        return json.toString();
    }
v6ylcynt

v6ylcynt5#

有JSON。simple是轻量级的JSON处理库,可以用来读取JSON或写入JSON文件。请尝试下面的代码

public static void main(String[] args) {

    JSONParser parser = new JSONParser();

    try (Reader reader = new FileReader("test.json")) {

        JSONObject jsonObject = (JSONObject) parser.parse(reader);
        System.out.println(jsonObject);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
b1uwtaje

b1uwtaje6#

try(InputStream inputStream =Thread.currentThread().getContextClassLoader().getResourceAsStream(Constants.MessageInput)){
            ObjectMapper mapper = new ObjectMapper();
            JsonNode jsonNode = mapper.readValue(inputStream ,
                    JsonNode.class);
            json = mapper.writeValueAsString(jsonNode);
        }
        catch(Exception e){
            throw new RuntimeException(e);
        }

相关问题