View Javadoc
1   /**
2    * Copyright By Grandsoft Company Limited.  
3    * 2012-7-5 下午07:37:57
4    */
5   package gboat2.base.core.util.json;
6   
7   import gboat2.base.core.web.EnumType;
8   
9   import java.lang.reflect.Method;
10  
11  import org.slf4j.Logger;
12  import org.slf4j.LoggerFactory;
13  
14  import net.sf.json.JSONObject;
15  import net.sf.json.JsonConfig;
16  import net.sf.json.processors.JsonValueProcessor;
17  
18  
19  /**
20   * 处理 JSON 字符串中枚举类型属性值的解析器
21   * @author lysming
22   * @since 1.0
23   * @date 2012-7-5
24   */
25  public class GboatJsonEnumValueProcessor implements JsonValueProcessor {
26      private final Logger logger = LoggerFactory.getLogger(GboatJsonEnumValueProcessor.class);
27      
28  	/**
29  	 * {@inheritDoc}   
30  	 * @see net.sf.json.processors.JsonValueProcessor#processArrayValue(java.lang.Object, net.sf.json.JsonConfig) 
31  	 */
32  	@Override
33  	public Object processArrayValue(Object value, JsonConfig jsonConfig) {
34  		return null;
35  	}
36  
37  	/**
38  	 * {@inheritDoc}   
39  	 * @see net.sf.json.processors.JsonValueProcessor#processObjectValue(java.lang.String, java.lang.Object, net.sf.json.JsonConfig) 
40  	 */
41  	@Override
42  	public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
43  		if(value instanceof Enum){
44  			Enum<?> e = (Enum<?>)value;
45  			String desc = e.name();
46  			try {
47  				Method m = e.getClass().getMethod("getDesc");
48  				if(m!=null){
49  					desc = (String) m.invoke(e);
50  				}
51  			} catch (Exception e1) {
52  			    logger.error("解析 JSON 串中的枚举类型值失败:key=[{}], value=[{}]", key, value);
53  			    logger.error("", e);
54  			} 
55  			EnumType en = new EnumType(e.name(),e.ordinal(),desc);
56  			return JSONObject.fromObject(en);
57  		}
58  		
59  		return null;
60  	}
61  
62  }