Java - Cara Maca File JSON minangka String

Ing kiriman iki, kita bakal nemokake cara maca file JSON minangka variabel String ing Jawa. Kadhangkala iki migunani, utamane ing tes API yen sampeyan pengin POST muatan JSON menyang titik pungkasan.

Sampeyan bisa nyelehake muatan JSON ing file, banjur waca file JSON minangka String lan gunakake minangka badan panjaluk POST.



Waca File JSON minangka String

Umpama kita duwe file JSON ing lokasi ing ngisor iki:


src/test/resources/myFile.json

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

Banjur kita bisa nggunakake kode Java ing ngisor iki kanggo maca file JSON ing ndhuwur minangka 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)));
} }

Output:



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