3 回答

TA貢獻1797條經驗 獲得超4個贊
您可以將 omitempty 標記與指針結構一起使用。在這種情況下,如果指針為零,則不會編組字段。(https://play.golang.org/p/7DihRGmW0jZ) 例如
package main
import (
"encoding/json"
"fmt"
)
type Test struct {
ID *int `json:"id,omitempty"`
Active *bool `json:"active,omitempty"`
Object *interface{} `json:"objects,omitempty"`
}
func main() {
var result Test
id:= 1
active := true
result.ID = &id
result.Active = &active
b, err := json.Marshal(result)
if err != nil {
panic(err)
}
fmt.Printf("%s\n", b)
}

TA貢獻1784條經驗 獲得超7個贊
使用的解決方案omitempty通常是最簡單的,但這里有一個替代解決方案,可用于更復雜的場景。這利用了這樣一個事實,即只要結構相同,即使標簽不同,值也可以轉換為另一種類型:https : //play.golang.org/p/ZT6gbhsXxmD
type Test struct {
ID int `json:"id"`
Active bool `json:"active"`
Object []Object `json:"objects,omitempty"`
}
type Test2 struct {
ID int `json:"id"`
Active bool `json:"active"`
Object []Object `json:"-"`
}
func main() {
var t Test
t.ID = 1
t.Active = true
t.Object = make([]Object, 1)
fmt.Println("Test:")
json.NewEncoder(os.Stdout).Encode(t)
fmt.Println("Test2:")
t2 := Test2(t)
json.NewEncoder(os.Stdout).Encode(&t2)
}
這在很多情況下都很有用,例如,您不想在發送到 JSON 之前從字段中刪除值,或者您有更復雜的數據結構。

TA貢獻1712條經驗 獲得超3個贊
省略值的簡單方法是使用omitemptyjson 的標簽并編寫一個返回對象的方法,如下所示:
package main
import (
"encoding/json"
"fmt"
"os"
)
type Test struct {
ID int `json:"id"`
Active bool `json:"active"`
Object []Object `json:"objects,omitempty"`
}
type Object struct {
TEMP string
}
func (t Test) getData() Test {
return Test{ID: t.ID, Active: t.Active}
}
func main() {
var t Test
t.ID = 1
t.Active = true
t.Object = make([]Object, 1)
fmt.Println(t)
fmt.Println(t.getData())
json.NewEncoder(os.Stdout).Encode(t)
fmt.Println("--------")
json.NewEncoder(os.Stdout).Encode(t.getData())
}
結果如下:
{1 true [{}]}
{1 true}
{"id":1,"active":true,"objects":[{"TEMP":""}]}
--------
{"id":1,"active":true}
- 3 回答
- 0 關注
- 140 瀏覽
添加回答
舉報