【问题标题】:Read json file from resources and convert it into json string in JAVA [closed]从资源中读取json文件并将其转换为JAVA中的json字符串[关闭]
【发布时间】:2020-04-27 19:49:45
【问题描述】:

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

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

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

【问题讨论】:

  • 您对要使用的库或框架有限制吗?请添加更多细节,让人们更好地帮助你:)

标签: java json configuration


【解决方案1】:

将 json 移动到资源文件夹中的文件 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 对象。

例如。使用杰克逊你可以做到

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

【讨论】:

  • 请注意,如果您将代码构建到 .jar 中,此方法将不起作用。使用读取输入流(例如,请参阅@jschnasse stackoverflow.com/a/59677244/1559962 对此问题的答案)
【解决方案2】:

使用 from 资源传递你的文件路径:

例子:如果你的resources -> folder_1 -> filename.json那么传入

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();
    }

【讨论】:

    【解决方案3】:

    有 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();
        }  
    

    【讨论】:

      【解决方案4】:

      根据我的经验,这是从类路径读取文件最可靠的模式。[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

      [2]Try With Resources vs Try-Catch

      [3]https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core

      【讨论】:

      • 刚刚把这个创建的 jsonNode 写成字符串。 json = mapper.writeValueAsString(jsonNode);谢谢
      • 这在 Enum 初始化程序块中不起作用,但在这种情况下用 InputStream json = getClass().getClassLoader().getResourceAsStream(templateFile) 替换 try 资源有效。
      【解决方案5】:

      有很多方法可以做到这一点:

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

      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);
      }
      

      【讨论】:

      • resourceToString 有错误?它说找不到要前往的声明
      【解决方案6】:
      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);
              }
      

      【讨论】:

      • @jschnasse 该死,感觉很糟糕......
      猜你喜欢
      • 2013-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-26
      • 2019-07-08
      • 1970-01-01
      相关资源
      最近更新 更多