任意に定義する Java クラス Object のリストを JSON にする時に、GSON を使用した理由
次の理由から、GSON が便利だった。
・任意に定義する Java クラスの要素で出力対象の要素を限定できること。
・デフォルトで Javaクラスのフィールド名が、JSONで Key名になり、簡単に特定のフィールドだけ、指定する名称を Key名にできること。
この要求で、Google GSON 利用のソリューションは、、、
・任意の要素=フィールドだけを対象にするには、@Expose アノテーションを対象jフィールドに付与した上で、GsonBuilderで Gsonを生成する時に、
excludeFieldsWithoutExposeAnnotation() で生成する。
・フィールド名がJSONのキー名にならないように、対象フィールドに、@SerializedName アノテーションで JSON でのキー名を指定する。
サンプル、、、
import java.util.Date;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* UserItem
*/
public class UserItem{
@Expose public long id;
@Expose public String name;
@Expose public int point;
public String address;
@Expose @SerializedName("cdt") public Date created_dt;
public UserItem(long id, String name, int point, String address, Date created_dt){
this.id = id;
this.name = name;
this.point = point;
this.address = address;
this.created_dt = created_dt;
}
}
// setDateFormat で日付の出力書式を設定
// @Expose が付いていないフィールドを対象外にする。
Gson gson = new GsonBuilder()
.setDateFormat("yyyy/MM/dd")
.excludeFieldsWithoutExposeAnnotation()
.create();
List<UserItem> list = new ArrayList<UserItem>();
// インデント、空白3文字で出力を JsonWriter で設定
// com.google.gson.reflect.TypeToken → java.lang.reflect.Type
Type collectionType = new TypeToken<Collection<UserItem>>(){}.getType();
JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream("output/users.json"), "UTF-8"));
writer.setIndent(" ");
gson.toJson(list, collectionType, writer);
writer.flush();
writer.close(); // close を忘れずに。。