码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-06-24 14:23:50      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

使用 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;    
}

 

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

标签:

原文地址:http://www.cnblogs.com/huey/p/4597242.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!