GSON属性カスタマイズ

5149 ワード


エンティティのすべての属性をエクスポートする必要はなく、一部の属性をJsonにエクスポートしたい場合があります.
バージョンのアップグレードに伴ってエンティティクラスが変更される場合があります.
出力のjsonをデフォルトでフォーマットしたい場合があります.
... ...
次の例を見てください.
エンティティークラス:
public enum ClientIdEnum {
    APP_GAME(1) // 1:    
    , KITTYPLAY_2V(22) // 22:    
    ;
    private final int value;

    private ClientIdEnum(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

 
public class AppInfo {
	
	public String name;//      
	
	@ClientLimit(closeAll = true)
	public String extendMes ;//      
	
	@ClientLimit(open = {ClientIdEnum.KITTYPLAY_2V,ClientIdEnum.APP_GAME})
	public String pic;//        /       
	
	@ClientLimit(close = {ClientIdEnum.APP_GAME})
	public Mes mes = new Mes();//           

	@Since(value = 1.3)
	public String imgs;//    >=1.3         
	
	@Until(value = 1.2)
	public String banner;//    <1.2         
	
	public AppInfo(){
		this.name = "   ";
		this.pic = "http://pic.png";
		this.imgs = "http://imgs1.png#http://imgs2.png";
		this.banner = "http://banner.png";
		this.extendMes = "    ";
	}
}

 
@Target({ElementType.FIELD}) 
@Retention(RetentionPolicy.RUNTIME) 
@Documented 
@Inherited
public @interface ClientLimit {
	/**
	 * @Title: open
	 * @Description:          ,  json  
	 * @param @return        
	 * @return ClientIdEnum[]        
	 * @throws
	 */
	ClientIdEnum[] open() default {};
	
	/**
	 * @Title: close
	 * @Description:         ,   json  
	 * @param @return        
	 * @return ClientIdEnum[]        
	 * @throws
	 */
	ClientIdEnum[] close() default {};
	
	/**
	 * @Title: closeAll
	 * @Description:         ,   json  
	 * @param @return        
	 * @return boolean        
	 * @throws
	 */
	boolean closeAll() default false;
}

 
public class ClientIdExclusionStrategy implements ExclusionStrategy {

	private ClientIdEnum clientId = null;
	
	public ClientIdExclusionStrategy(ClientIdEnum clientId){
		this.clientId = clientId;
	}
	@Override
	public boolean shouldSkipField(FieldAttributes f) {
		boolean filter = false;
		
		ClientLimit clientLimit = f.getAnnotation(ClientLimit.class);
		if(clientLimit != null){
			boolean closeAll = clientLimit.closeAll();
			if(closeAll){
				filter = true;
			}else {
				ClientIdEnum[] open = clientLimit.open();
				ClientIdEnum[] close = clientLimit.close();
				if(open.length > 0){
					filter = true;
					for(ClientIdEnum clientIdEnum:open){
						if(clientId == clientIdEnum){
							filter = false;
							break;
						}
					}
				}else if (close.length > 0) {
					filter = false;
					for(ClientIdEnum clientIdEnum:close){
						if(clientId == clientIdEnum){
							filter = true;
							break;
						}
					}
				}
			}
		}
		return filter;
	}

	@Override
	public boolean shouldSkipClass(Class<?> clazz) {
		// TODO Auto-generated method stub
		return false;
	}

}

 
 
public class Test  extends TestCase{

	public void testGson(){
		AppInfo appInfo = new AppInfo();
		//     Gson      GsonBuilder,   test1  Gson gson = new Gson();  
        Gson gson = new GsonBuilder()  
//        .excludeFieldsWithoutExposeAnnotation() //         @Expose       
        .enableComplexMapKeySerialization() //  Map key          
        .serializeNulls() //    null,    null   ;  null      
        .setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")//             
//        .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)//         , :        @SerializedName       .  
        .setPrettyPrinting() // json     .  
        .setVersion(1.2)    //            ,            ,                                .  
                            //@Since(   )          .      ,          ,    
                            //@Until(   )        ,GsonBuilder.setVersion(double)      .  
        .setExclusionStrategies(new ClientIdExclusionStrategy(ClientIdEnum.APP_GAME))//        
//        .registerTypeAdapter(type, typeAdapter) //      ,       type   ,  typeAdapter  ,        
        .create(); 
        System.out.println(gson.toJson(appInfo));
	}
}