JSON(3):Java的Date類型轉換為符合json文法的字串遇到的問題及其解決辦法

來源:互聯網
上載者:User

接著上篇文章,先看下面的代碼:

Person.java :

public class Person {private Date hire;public Date getHire() {return hire;}public void setHire(Date hire) {this.hire = hire;}public Person() {super();}public Person(Date hire) {super();this.hire = hire;}}

Test.java :

public class Test {public static void main(String[] args) {test();}public static void test(){Person p=new Person(new Date());JSONObject json=JSONObject.fromObject(p);String json_str=json.toString();System.out.println(json_str);}}

運行程式得到:

{"hire":{"date":20,"day":4,"hours":17,"minutes":21,"month":5,"seconds":16,"time":1371720076781,"timezoneOffset":-480,"year":113}}

這顯然不是我們希望得到的格式。那麼怎麼解決呢?其實匯入的相關jar包裡已經給我們預留了我們所需要的介面JsonValueProcessor

我們可以寫一個轉換器,並且選擇實現架構給我們預留的介面JsonValueProcessor,實現介面中的方法,在這些方法裡實現所需要的轉換邏輯。

DateProcessor.java :

public class DateProcessor implements JsonValueProcessor {private String pattern="yyyy-MM-dd";public void setPattern(String pattern) {this.pattern = pattern;}@Overridepublic Object processArrayValue(Object arg0, JsonConfig arg1) {Date date=(Date)arg0;SimpleDateFormat sdf=new SimpleDateFormat(pattern);return sdf.format(date);}@Overridepublic Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {Date date=(Date)arg1;SimpleDateFormat sdf=new SimpleDateFormat(pattern);return sdf.format(date);}}

然後改寫Test.java :

public class Test {public static void main(String[] args) {test();}public static void test(){Person p=new Person(new Date());DateProcessor processor=new DateProcessor();JsonConfig config=new JsonConfig();config.registerJsonValueProcessor(Date.class,processor);JSONObject json=JSONObject.fromObject(p,config);String json_str=json.toString();System.out.println(json_str);}}

此時再運行程式得到:

{"hire":"2013-06-20"}

這樣就可以將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.