See More

import java.util.*; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import kr.inflearn.BookDTO; public class Project01_A { public static void main(String[] args) { //Object(BookDTO) -> JSON(String) BookDTO dto=new BookDTO("ÀÚ¹Ù", 21000,"¿¡ÀÌÄÜ", 670); Gson g=new Gson(); String json=g.toJson(dto); System.out.println(json); // {"title":"ÀÚ¹Ù","price":21000,"company":"¿¡ÀÌÄÜ","page":670} //JSON(String) -> Object(BookDTO) BookDTO dto1=g.fromJson(json, BookDTO.class); System.out.println(dto1); // BookDTO [title=ÀÚ¹Ù, price=21000, company=¿¡ÀÌÄÜ, page=670] System.out.println(dto1.getTitle()+"\t"+dto1.getPrice()); // Object(List) -> JSON(String) : [{ },{ }.....] List lst=new ArrayList(); lst.add(new BookDTO("ÀÚ¹Ù1", 21000,"¿¡ÀÌÄÜ1", 570)); lst.add(new BookDTO("ÀÚ¹Ù2", 31000,"¿¡ÀÌÄÜ2", 670)); lst.add(new BookDTO("ÀÚ¹Ù3", 11000,"¿¡ÀÌÄÜ3", 370)); String lstJson=g.toJson(lst); System.out.println(lstJson); // JSON(String) -> Object(List) List lst1=g.fromJson(lstJson, new TypeToken>(){}.getType()); for(BookDTO vo : lst1) { System.out.println(vo); } } }