JAVA
[JAVA] GSON 라이브러리
탈탈99
2021. 7. 12. 19:53
반응형
GSON은 Java에서 JSON 형태를 좀 더 쉽게 다룰 수 있게 해주는 라이브러리이다.
예제 코드는 아래와 같다.
1. toJson
public void printFileJSON(List<Todo> todoList) {
File file = new File("todo.json");
Gson gson = new Gson();
try {
FileWriter fileWriter = new FileWriter(file);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print("[");
for (Todo todo : todoList) {
//JSON 변환
String jsonInString01 = gson.toJson(todo);
printWriter.print(jsonInString01);
printWriter.print(",");
}
printWriter.print("]");
printWriter.close();
} catch(IOException e) {
e.printStackTrace();
}
printTodoList(todoList);
}
2. fromJson
List<Todo> todoList = null;
File file = new File("todo.json");
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String jsonString = br.readLine();
Todo[] array = gson.fromJson(jsonString, Todo[].class);
todoList = Arrays.asList(array);
} catch(IOException e) {
e.printStackTrace();
}
TodoProcessor todoProcessor = todoProcessorMapping.get(TodoMenu.CREATE);
for (Todo todo : todoList) {
todoProcessor.run(todo);
}
ioHelper.printTodoList(todoRepository.findAll());
728x90
반응형