글
Gson을 이용하여 static variable을 serialize하기
Gson 공부
2014. 2. 6. 16:23
Gson은 class의 static field를 transient하게 기본적으로 취급하는것 같다. 이 때문에 gson을 통해서 직렬화를 해도 값이 나타지가 않는다. 이를 해결하기 위해서 GsonBuilder의 설정을 이용하면 해결되는것을 볼 수 있다.
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | package pkg1; import java.lang.reflect.Type; import com.google.gson.*; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Modifier; import java.util.*; class Bar{ static int account = 5; Collection<Integer> collection = new ArrayList<Integer>(); Bar(){ collection.add(5); collection.add(6); } } public class MytestClass { public static void main(String[] args) { Bar _bar = new Bar(); Gson gson_bar = new GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create(); String json = gson_bar.toJson(_bar,_bar.getClass()); System.out.println("_Bar: "+json); Bar _bar_2 = new Bar(); _bar_2 = gson_bar.fromJson(json, Bar.class); Iterator<Integer> iterator = _bar_2.collection.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } System.out.println(_bar_2.collection.size() ); } } |
map도 잘됨
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | package pkg1; import java.lang.reflect.Type; import com.google.gson.*; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Modifier; import java.util.*; class Foo<T>{ T value; void setValue(T value){ this.value = value; } } class Bar{ static int account = 5; Collection<Integer> collection = new ArrayList<Integer>(); static Map<Integer, String> map = new HashMap<Integer,String>(); Bar(){ collection.add(5); collection.add(6); map.put(100, "aaa"); map.put(200, "bbb"); } } 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); Bar _bar = new Bar(); Gson gson_bar = new GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create(); json = gson_bar.toJson(_bar,_bar.getClass()); System.out.println("_Bar: "+json); Bar _bar_2 = new Bar(); _bar_2 = gson_bar.fromJson(json, Bar.class); Iterator<Integer> iterator = _bar_2.collection.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } iterator = _bar_2.map.keySet().iterator(); while(iterator.hasNext()){ System.out.println(_bar_2.map.get((Integer)iterator.next())); } System.out.println(_bar_2.collection.size() ); } } |