package exam.java.io;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class CustometToJson {
public static void main(String[] args) throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("customer.data"));
ArrayList custs = (ArrayList)ois.readObject();
Gson gson = new Gson();
for(Customer cust : custs) {
// System.out.println(cust.toString());
System.out.println(gson.toJson(cust)); //객체 하나를 JSON 문자열로 출력
}
System.out.println(gson.toJson(custs)); //리스트의 모든 객체를 JSON 배열로 출력
String custsTest = "[{\"name\":\"홍길동\",\"gender\":\"M\",\"email\":\"hong@hong.com\",\"birthYear\":1980},"
+ "{\"name\":\"홍길서\",\"gender\":\"M\",\"email\":\"seo@hong.com\",\"birthYear\":1985}]";
java.lang.reflect.Type collectionType = new TypeToken>(){}.getType();
ArrayList custs2 = gson.fromJson(custsTest, collectionType); //문자열을 리스트객체로 변환
for(Customer c2 : custs2) {
System.out.println(c2.toString());
}
}
}
|