Json-lib - java.util.Date 轉換問題

來源:互聯網
上載者:User

標籤:

使用 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 轉換問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.