1.json.Marshalでstructにomitemptyを指定して nill -> null を行う
(1) tructにomitemptyを指定
(2) nill, ”” , false を判定
(3) nill の場合、nill -> null を行う
2.結論
・omitemptyを指定しても、実行結果ではフィールドは省略されていない
2.code
package main
import (
"encoding/json"
"fmt"
)
type Employee_s struct {
Name interface{} `json:"name,omitempty"`
Id *interface{} `json:"id,omitempty"`
}
func main() {
var NULL interface{};
employee := [6] Employee_s{}
employee[0].Name = "Name_1"
employee[1].Name = nil
employee[2].Name = NULL
employee[3].Name = ""
employee[4].Name = ``
employee[5].Name = false
isNull_1 := interface{}(nil)
isNull_2 := interface{}(2)
isNull_3 := interface{}("")
var isNull_4 interface{}
var isNull_5 interface{}
var isNull_6 interface{}
isNull_4 = nil
isNull_5 = false
isNull_6 = true
employee[0].Id = &isNull_1
employee[1].Id = &isNull_2
employee[2].Id = &isNull_3
employee[3].Id = &isNull_4
employee[4].Id = &isNull_5
employee[5].Id = &isNull_6
json_string, _ := json.Marshal(employee)
fmt.Println(string(json_string))
}
・実行結果
# go run test.go
[{"Name":"Name_1","id":null},{"Name":null,"id":2},{"Name":null,"id":""},{"Name":"","id":null},{"Name":"","id":false},{"Name":false,"id":true}]
#