標籤:
使用 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@AllArgsConstructorpublic class Student { private String studNo; private String studName; private char gender; private Date birthday; }
Json-lib - java.util.Date 轉換問題