내용

글번호 455
작성자 heojk
작성일 2017-02-18 07:53:14
제목 객체를 JSON으로 변환하고 JSON을 객체로 변환하는 예
내용
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());
		}
	}
}