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

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

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

  1. public class Person {
  2.     private String name;
  3.     private Date birthday;
  4.     public void setName(String name) {
  5.         this.name = name;
  6.     }
  7.     public String getName() {
  8.         return name;
  9.     }
  10.     public void setBirthday(Date birthday) {
  11.         this.birthday = birthday;
  12.     }
  13.     public Date getBirthday() {
  14.         return birthday;
  15.     }
  16. }

转换的代码是这样的:

  1. JSONObject jsonPerson = JSONObject.fromObject(personData);  //personaData是json串
  2. 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串时,日期属性的格式不符合习惯,后来好不容易才找到了这个问题的解决办法,虽然是抄别人的,但也发一贴为以后其他人更容易找到答案出点力,呵呵。废话少说,其实解决方法很简单,把转换代码改成这样:

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

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

原文地址:https://www.cnblogs.com/Feiyang-Lafe/p/5787742.html