11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MarshalJSONをオーバーライドしてオリジナルJSONへエンコーディング

Last updated at Posted at 2016-04-29

はじめに

Go言語でカスタマイズされたJSONの生成方法を実例を交えて説明します
RestFulAPIを実装する等の場合に使います

やる内容

type MyTime struct {
	Time time.Time `json:"time"`
}

上記のtime.Time型を持つ構造体MyTimeから

{"time":"2016-04-30 01:30:54"

というような形式のJSONへとエンコードすることが目的です。

そのまま構造体をJSONへエンコードすると

plane.go
package main

import (
	"fmt"
	"time"
	"encoding/json"
)

type MyTime struct {
	Time time.Time `json:"time"`
}

func main() {
	// MyTime初期化
	dt, _ := time.Parse("2006/01/02 15:04:05", "2016/04/01 05:21:33")
	mt := &MyTime{Time:dt}
	
	// JSON変換
	m_bytes, _ := json.Marshal(mt)
	
	// 出力
	fmt.Println(string(m_bytes))
}
出力
{"time":"2016-04-01T05:21:33Z"}

このTとZが今回は不要です。

ちなみに、timeパッケージの公式を見ると

time#MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

> MarshalJSON implements the json.Marshaler interface. The time is a quoted string in RFC 3339 format, with sub-second precision added if present.

とあり、TとかZは、RFC3339という表記の規格によるもので、time.Time`型はデフォルトではこの規格ということです。

このままでは希望通りの形式にならないので、`MarshalJSON`をオーバーライドしてJSONをカスタマイズします。

## MashalJSONをオーバーライドする

```go:overrideMarshalJSON.go
package main

import (
	"fmt"
	"time"
	"encoding/json"
)

type MyTime struct {
	Time time.Time `json:"time"`
}

// @Override
func (m *MyTime) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf("{\"time\":\"%s\"}", m.Time.Format("2006-01-02 15:04:05"))), nil
}


func main() {
	// MyTime初期化
	dt, _ := time.Parse("2006/01/02 15:04:05", "2016/04/01 05:21:33")
	mt := &MyTime{Time:dt}
	
	// JSON変換
	m_bytes, _ := json.Marshal(mt)
	
	// 出力
	fmt.Println(string(m_bytes))
}
出力
{"time":"2016-04-01 05:21:33"}

time.Timeで定義されていたMarshalJSONメソッドがオーバーライドされて希望通りになりました!

11
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?