내용

글번호 455
작성자 heojk
작성일 2017-02-18 07:53:14
제목 객체를 JSON으로 변환하고 JSON을 객체로 변환하는 예
내용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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<customer> custs = (ArrayList<customer>)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<arraylist<customer>>(){}.getType();
    ArrayList<customer> custs2 = gson.fromJson(custsTest, collectionType); //문자열을 리스트객체로 변환
    for(Customer c2 : custs2) {
      System.out.println(c2.toString());
    }
  }
}
</customer></arraylist<customer></customer></customer>