Gson convert date data to specific JSON data

Source: Internet
Author: User
Tags tojson

When passing data through JSON, it is often necessary to pass the date, which in Java can be converted to JSON data in a specific format by Gson.

1. Normal Gson Conversion Date

    void Query (httpservletrequest request, httpservletresponse response, Registerservice Service)            throws Exception {         = Integer.parseint (Request.getparameter ("id"));         = Service.getregisterbyid (ID);         New Gson ();         = Gson.tojson (register);        SYSTEM.OUT.PRINTLN (JSON);        Response.getwriter (). write (JSON);    }

Date format after conversion:

Front Screen display:

2. If you need to convert the date format to data in a specific date format:

    //Enquiry     Public voidQuery (httpservletrequest request, httpservletresponse response, Registerservice service)throwsException {Integer ID= Integer.parseint (Request.getparameter ("id")); Register Register=Service.getregisterbyid (ID); //Convert the date format, or you can new Gsonbuilder (). Setdateformat ("Yyyy-mm-dd HH:mm:ss"). Create ();Gson Gson =NewGsonbuilder (). Setdateformat ("Yyyy-mm-dd"). Create (); String JSON=Gson.tojson (register);        SYSTEM.OUT.PRINTLN (JSON);    Response.getwriter (). write (JSON); }

Converted date JSON:

The format of the date displayed by the foreground interface:

Gson convert date data to specific JSON data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.