ITeye博客

使用json-lib的JSONObject.toBean( )时碰到的日期属性转换的问题

yiyu · 2009-01-22 16:21 · java · 编程语言 · json · Bean · Markdown

今天碰到这样一个问题: 当前台以JSON格式向后台传递数据的时候,对于数据中的日期属性,无法正常转换为相应的Date属性。 JSON数据是这样的: {"birthday":"1980/01/01","name":"testname"}

我要转换成的类是这样的:

public class Person { private String name; private Date birthday;

public void setName(String name) {
	this.name = name;
}

public String getName() {
	return name;
}

public void setBirthday(Date birthday) {
	this.birthday = birthday;
}

public Date getBirthday() {
	return birthday;
}

}

转换的代码是这样的:

JSONObject jsonPerson = JSONObject.fromObject(personData); //personaData是json串 Person person = (Person)JSONObject.toBean(jsonPerson, Person.class);

转换时并不抛出例外,而是在日志中打出以下警告信息: Can't transform property 'birthday' from java.lang.String into java.util.Date. Will register a default Morpher

在网上搜了一遍,发现了很多关于进行相反方向转换时的帖子,即使用json-lib将bean转成json串时,日期属性的格式不符合习惯,后来好不容易才找到了这个问题的解决办法,虽然是抄别人的,但也发一贴为以后其他人更容易找到答案出点力,呵呵。废话少说,其实解决方法很简单,把转换代码改成这样:

JSONObject jsonPerson = JSONObject.fromObject(personData); String[] dateFormats = new String[] {"yyyy/MM/dd"}; JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats)); Person person = (Person)JSONObject.toBean(jsonPerson, Person.class);

想深究原因的人可以参看json-lib和ezmorpher的相关文档。

评论(1)

  1. #1 楼 · hlgyyx · 2009-09-09 11:57

    用到了,支持一下!

评论功能维护中,当前仅展示历史评论。