728x90
반응형
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);
    }
 
}


728x90
반응형
블로그 이미지

nineDeveloper

안녕하세요 현직 개발자 입니다 ~ 빠르게 변화하는 세상에 뒤쳐지지 않도록 우리모두 열심히 공부합시다 ~! 개발공부는 넘나 재미있는 것~!

,