Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Hướng Dẫn Java: Đọc File JSON Thành String Cho API Testing

Trong bài viết này chúng ta sẽ xem cách đọc file JSON như một biến String trong Java. Điều này đôi khi hữu ích, đặc biệt trong API testing khi bạn muốn POST một JSON payload đến endpoint.

Bạn có thể đặt JSON payload trong file, sau đó đọc file JSON như String và dùng nó làm body của POST request.

Đọc JSON File Thành String

Giả sử chúng ta có file JSON ở vị trí sau:

src/test/resources/myFile.json

{
  "name":"David",
  "age":30,
  "hobbies":["Football","Cooking","Swimming"],
  "languages":{"French":"Beginner","German":"Intermediate","Spanish":"Advanced"}
}

Sau đó chúng ta có thể dùng code Java sau để đọc file JSON trên như String:

import java.nio.file.Files;
import java.nio.file.Paths;

public class ReadJsonAsString {
    public static void main(String[] args) throws Exception {
        String file = "src/test/resources/myFile.json";
        String json = readFileAsString(file);
        System.out.println(json);
    }
    public static String readFileAsString(String file) throws Exception {
        return new String(Files.readAllBytes(Paths.get(file)));
    }
}

Đầu ra:

{
  "name":"David",
  "age":30,
  "hobbies":["Football","Cooking","Swimming"],
  "languages":{"French":"Beginner","German":"Intermediate","Spanish":"Advanced"}
}