"omitempty"のメモ - golang
2020-06-25
json.Marshal
はomitempty
が値型string
に設定されていれば空文字を出力する。
フィールド自体不要な場合は、ポインタ型string
にするといい。
package main
import (
"encoding/json"
"fmt"
)
type ValueSlice struct {
Values []V `json:"b,omitempty"`
}
type PtrSlice struct {
Values []*V `json:"b,omitempty"`
}
type ValueStruct struct {
Value V `json:"value,omitempty"`
}
type PtrStruct struct {
Value *V `json:"value,omitempty"`
}
type V struct {
Value string `json:"value"`
}
func main() {
v1 := &ValueSlice{}
v2 := &PtrSlice{}
v3 := &ValueStruct{}
v4 := &PtrStruct{}
bv1, _ := json.Marshal(v1)
bv2, _ := json.Marshal(v2)
bv3, _ := json.Marshal(v3)
bv4, _ := json.Marshal(v4)
fmt.Printf("bv1: %v\n", string(bv1))
fmt.Printf("bv2: %v\n", string(bv2))
fmt.Printf("bv3: %v\n", string(bv3))
fmt.Printf("bv4: %v\n", string(bv4))
}
出力結果
bv1: {}
bv2: {}
bv3: {"value":{"value":""}}
bv4: {}