package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
public class JSONMain {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file = new File("./INPUT/json_data.txt");
if(file.exists()) {
System.out.println("is exists!!");
}else {
System.out.println("is not exists!!");
}
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = null;
StringBuilder sb = new StringBuilder();
while((line = br.readLine()) != null) {
sb.append(line);
}
Gson gson = new Gson();
//Person person = gson.fromJson(sb.toString(), new TypeToken<Person>(){}.getType());
Person person = gson.fromJson( sb.toString() , Person.class);
System.out.println(person.name);
System.out.println(person.age);
System.out.println(person.married);
System.out.println(person.children[0].name + " " + person.children[0].age);
System.out.println(person.children[1].name + " " + person.children[1].age);
System.out.println(person.vaccine.get("2nd"));
//Gson gson = new Gson();
String json = gson.toJson(person);
System.out.println(json);
JsonElement jsonElement = JsonParser.parseString(json);
System.out.println(jsonElement.toString());
JsonObject obj = jsonElement.getAsJsonObject();
obj.get("name").getAsString();
System.out.println(obj.get("name").getAsString());
String filePath = "./INPUT/json_data.txt";
Path path = Paths.get(filePath);
String wholeData = Files.readString(path);
//Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(wholeData, JsonObject.class);
System.out.println(wholeData);
}
}
JSON -> Object using Path
2023. 7. 14. 17:55