JSON DATE类型转换错误,如何解决?

之前请教的一个问题,自动把json转换为domain

当时的作法如下面的代码.

现在碰到的问题是,一个nullable的时间类型的字段, json无值的时候报错.

Failed to convert property value of type 
    'org.codehaus.groovy.grails.web.json.JSONObject$Null' 
    to required type 'java.util.Date' for property 'firstFireTime'
class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {

    @Override
    public void registerCustomEditors(PropertyEditorRegistry registry) { 
        def formats = GrailsConfig.get("grails.date.formats", List.class)?:
                    ["yyyy-MM-dd HH:mm:ss",
					 "yyyy-MM-dd'T'HH:mm:ss",
					 "yyyy-MM-dd"];
		registry.registerCustomEditor(Date.class, new CustomDateBinder(formats)); 
	} 
}
class CustomDateBinder extends PropertyEditorSupport {
	private final List<String> formats;
	
	public CustomDateBinder(List formats) {
		List<String> formatList = new ArrayList<String>(formats.size());
		for (Object format : formats) {
			formatList.add(format.toString()); 
		}
		this.formats = Collections.unmodifiableList(formatList);
	}

	@Override
	public void setAsText(String s) throws IllegalArgumentException {
		if (s){
			for (String format : formats) {
				
				SimpleDateFormat df = new SimpleDateFormat(format);
				try {
					setValue(df.parse(s));
					return;
				} catch (ParseException e) {
					// Ignore
				}
			}
		}
	}
}

在JSON进行转换时,会将null转换为org.codehaus.groovy.grails.web.json.JSONObject$Null,所以需要在CustomDateBinder中添加setValue方法进行处理,参见如下代码:

class CustomDateBinder extends PropertyEditorSupport {
    ...
	public CustomDateBinder(List formats) {...}
	public void setAsText(String s) throws IllegalArgumentException {...}

    @Override
    public void setValue(Object value) {	
        if(value){
            if (JSONObject.NULL.getClass().isInstance(value) ) {
                super.setValue(null);
            } else {				
                super.setValue(value);			
            }
        }else{
            super.setValue(null);
        }
    }
}

By 匿名用户 - Posted on 25 五月 2011