GSON フィールド除外アノテーションを考えた。

Google gson には、@Expose というアノテーションを付与したフィールドだけを JSONシリアライズ対象に
する機能があります。
でも逆に、特殊なアノテーションを付与してそのフィールドをシリアライズ対象外にする。
という機能がありません。
ほとんどが、expose 対象で、除外したいのだけを指定したい場合にこのままでは使いにくいです。
そこで、com.google.gson.ExclusionStrategy を実装して
特殊な指定のアノテーションが付いたフィールドはJSONとして生成させない(シリアライズ対象外)
という機能を作りました。

package org.yipuran.gsonhelper;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
/**
 * シリアライズ除外アノテーション.
 */
public @interface Exclude{
}
package org.yipuran.gsonhelper;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
/**
 * @Exclude フィールド除外 Strategy.
 * @since 4.5
 */
public class ExcludeWithAnotateStrategy implements ExclusionStrategy{
	@Override
	public boolean shouldSkipClass(Class<?> clazz){
		return false;
	}
	@Override
	public boolean shouldSkipField(FieldAttributes f){
		return f.getAnnotation(Exclude.class) != null;
	}
}

Gson インスタンス生成

 new GsonBuilder().addSerializationExclusionStrategy( new ExcludeWithAnotateStrategy() ).create();

ただし、注意が必要です。
@Expose の指定による excludeFieldsWithoutExposeAnnotation() と併用した場合、
@Exclude が優先されて@Expose の効力はなくなる。

というこです。

これら、Exclude と、ExcludeWithAnotateStrategy を、
yipuran-gsonhelper Version 4.5 として更新しました。
https://github.com/yipuran/yipuran-gsonhelper