Golang time format solution for JSON

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Golang time format solution for JSON

1. Specify the number format when querying through the data, so you don't have to format it again.
2. Pass time. The time type wears an alias, and then implements the Marshaljson method for the alias class.

The following original comments from Golang

If an encountered value implements the Marshaler interface
and is not a nil pointer, Marshal calls its Marshaljson method
to produce JSON. If no Marshaljson method is present but the
Value implements encoding. Textmarshaler instead, Marshal calls
Its Marshaltext method.

//jsontest project Main.go PackageMainImport("Encoding/json"    "FMT"    "Time")typeJsontime time. Time//Implement its JSON serialization methodfunc(This jsontime) Marshaljson () ([]byte, error) {varStamp = FMT. Sprintf ("\"%s\ "", time. Time (this). Format ("2006-01-02 15:04:05"))return[]byte(stamp),Nil}typeTeststruct{Date Jsontime' JSON: ' Date 'Namestring   ' JSON: ' Name 'StateBOOL     ' JSON: ' state '}funcMain () {vart = test{} t.date = Jsontime (time. Now ()) T.name ="Hello World"T.state =trueBody, _: = json. Marshal (t) fmt. Println (string(body))}

Output Result:

{"date ":  "2016-11-04 13:42:24"  , " Name  ": " Hello World " ," state ": true  }  
Related Article

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.