Go:将空结构封送到json
我正在尝试将结构编组为json。当结构具有值时,它工作。但是,当结构没有值时,我无法访问网页: 去: 错误是否是因为json.Marshal无法封送空结构?请参见此处:Go:将空结构封送到json,go,Go,我正在尝试将结构编组为json。当结构具有值时,它工作。但是,当结构没有值时,我无法访问网页: 去: 错误是否是因为json.Marshal无法封送空结构?请参见此处: 什么错误?您明确地忽略了错误。检查一下可能会有帮助。另外,{[]}在Go中是无效语法。 type Fruits struct { Apple []*Description 'json:"apple, omitempty"' } type Description struct { Color string
什么错误?您明确地忽略了错误。检查一下可能会有帮助。另外,{[]}在Go中是无效语法。
type Fruits struct {
Apple []*Description 'json:"apple, omitempty"'
}
type Description struct {
Color string
Weight int
}
func Handler(w http.ResponseWriter, r *http.Request) {
j := {[]}
js, _ := json.Marshal(j)
w.Write(js)
}
package main
import "fmt"
import "encoding/json"
type Fruits struct {
Apple []*Description `json:"apple, omitempty"`
}
type Description struct {
Color string
Weight int
}
func main() {
j := Fruits{[]*Description{}} // This is the syntax for creating an empty Fruits
// OR: var j Fruits
js, err := json.Marshal(j)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(js))
}