글
Gson generic type을 deserialize하기
Gson 공부
2014. 2. 6. 15:13
Gson을 공부하는데 generic type의 클래스를 Deserialize하는데 문제가 생겼다.
https://sites.google.com/site/gson/gson-user-guide
에 보면 해결법이 있는데, Type class를 import해야하는데
어떤걸 import해야하는지몰라서 해멨었다.
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 31 | package pkg1; import java.lang.reflect.Type; import com.google.gson.*; import com.google.gson.reflect.*; class Foo<T>{ T value; void setValue(T value){ this.value = value; } } public class MytestClass { public static void main(String[] args) { Gson gson = new Gson(); Foo<Integer> foo = new Foo<Integer>(); foo.setValue(5); Type fooType = new TypeToken<Foo<Integer>>(){}.getType(); String json = gson.toJson(foo,fooType); System.out.println(json); Foo<Integer> bar = new Foo<Integer>(); bar = gson.fromJson(json, fooType ); System.out.println("bar: "+(int)bar.value); } } |