Json-lib - java.util.Date 转换问题

使用 JSON-lib 将 java.util.Date 对象直接转换成 JSON 字符串时,得到的通常不是想要格式:

System.out.println(JSONSerializer.toJSON(new Date()));
// {"date":24,"day":3,"hours":12,"minutes":39,"month":5,"seconds":46,"time":1435120786584,"timezoneOffset":-480,"year":115}

 

JavaBean 转 JSON

JsonValueProcessor jsonValueProcessor = new JsonValueProcessor() {
    private final String DATE_FORMAT = "yyyy-MM-dd";
    @Override
    public Object processObjectValue(String key, Object value, JsonConfig config) {
        if (value == null) {
            return "";
        }
        if (value instanceof Date) {
            return new SimpleDateFormat(DATE_FORMAT).format((Date) value);
        }
        return value.toString();
    }
    @Override
    public Object processArrayValue(Object value, JsonConfig config) {
        return null;
    }
};

JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(Date.class, jsonValueProcessor);
Student stud = new Student("1001", "huey", 'M', new Date());
String jsonStr = JSONSerializer.toJSON(stud, jsonConfig).toString();
System.out.println(jsonStr);    // {"birthday":"2015-06-24","gender":"M","studName":"huey","studNo":"1001"}

JSON 转 JavaBean

String jsonStr = "{'studNo':'1001','studName':'huey','gender':'M','birthday':'2014-04-13'}";
JSONObject jsonObj = JSONObject.fromObject(jsonStr);
JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[]{"yyyy-MM-dd"}));
Student stud = (Student) JSONObject.toBean(jsonObj, Student.class);
System.out.println(stud);    // Student(studNo=1001, studName=huey, gender=M, birthday=Sun Apr 13 00:00:00 CST 2014)

JavaBean 定义

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private String studNo;
    private String studName;
    private char gender;
    private Date birthday;    
}

 

posted on 2015-06-24 12:59  huey2672  阅读(339)  评论(0编辑  收藏  举报