GSON 간단 사용 예
멤버의 경우 private, public 구분 없고, set,get 메쏘드 불필요.
1. Serialize
class Model {
private String id = "111";
private String name = "model";
private String type;
};
Gson gson = new Gson();
Model model = new Model();
String jsonString = gson.toJson( model );
result)
{"id":"111","name":"model"}
2. 값이 null인 녀석도 표시
Gson gson = new GsonBuilder().serializeNulls().create();
Model model = new Model();
String jsonString = gson.toJson( model );
result)
{"id":"111","name":"model","type":null}
3. 이너 클래스 : static 클래스만 사용가능
class Model {
private String id = "111";
private String name = "model";
private String type;
private Item item = new Item();
public static class Item {
String title = "제목";
String msg;
};
};
result)
{"id":"111","name":"model","type":null,"item":{"title":"제목","msg":null}}
4. 오브젝트 배열
class Model {
private String id = "111";
private String name = "model";
private String type;
public ArrayList<Item> list = new ArrayList<Item>();
public static class Item {
String title = "제목";
String msg;
};
};
Model mode = new Model();
mode.list.add( new Item() );
mode.list.add( new Item() );
retuls)
{"id":"111","name":"model","type":null,"list":[{"title":"제목","msg":null},{"title":"제목","msg":null}]}
5. Generic type
class Model<T> {
private String id = "111";
private String name = "model";
private T type;
};
Type modelType = new TypeToken<Model<String>>() {}.getType();
gson.toJson( model, modelType );
기타 등등..
-_-;;