英文:
Go: Marshal empty struct into json
问题
我正在尝试将一个结构体转换为JSON。当结构体有值时,它可以正常工作。然而,当结构体没有值时,我无法访问网页:
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)
}
错误是因为json.Marshal无法将空结构体转换为JSON吗?
英文:
I'm trying to marshal a struct into json. It works when the struct has values. However, I'm unable to access the webpage when the struct has no value:
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)
}
Is the error because json.Marshal cannot marshal an empty struct?
答案1
得分: 1
请看这里:http://play.golang.org/p/k6d6y7TnIQ
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{}} // 这是创建一个空的 Fruits 的语法
// 或者:var j Fruits
js, err := json.Marshal(j)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(js))
}
英文:
See here: http://play.golang.org/p/k6d6y7TnIQ
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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论