日期:2014-05-16  浏览次数:20369 次

Struts2-json-plugin扩展,根据业务解析JSON

? ? ? ?在JQuery、Extjs等js框架流行时,JSON数据拼装的简化一直是个问题,在实际业务中,每一个action的function可能需要的JSON都不相同。

? ? ? ?StringBuffer拼写JSON再write出去本来是最灵活的,但是拼写的时候一是难于检查拼写正确性,二是难于维护,所以绝对不能考虑,否则会被后期维护会烦死。领域模型太过于死板,只能写一种业务的JSON。

? ? ? ?借鉴扩展Struts2-json-plugin,可以在Action的方法上增加annotation方式来反射拼写JSON,这样就可以将组装JSON的工作拆分出来,放到通用方法中。实际测试中虽然反射很慢,但是性能问题可以忽略不计,因为浏览器对JSON数据的解析有性能限制,一次不会解析太多数据。

? ? ? ?在原有@JSON标签基础上,增加了?JSONProperty[] 属性

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface JSON {
	
    String name() default "";

    boolean serialize() default true;

    boolean deserialize() default true;

    String format() default "";
    
    JSONProperty[] properties() default {};
}


@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface JSONProperty {

	String root() default "";

	String clazz() default "";
	
	JSONType type() default JSONType.list;

	String[] property() default {};
}

? ??JSONType根据拼写规则不同,分为list,lazyTree,eagerTree,lazyTreeGrid,eagerTreeGrid,checkEagerTree,checkLazyTree,comboList几种,使用效果如下

?

private List<Councils> list;
/**
** 解析Action中的属性——list,并解析list中的对象中的id、name、created以及Councils关联对象 manageOrganization的id、name属性,Councils关联对象 manageUser的id、name属性
**/

@JSON(properties = @JSONProperty(root = "list", property = { "id", "name", "created", "manageOrganization.id", "manageOrganization.name","manageUser.id","manageUser.name" }))
	public String list() {
		return super.list();
	}

?

? 在实际使用过程中碰到很多问题,但是达到预期效果

? ?

?