Go:将Marshal空结构转换为json

时间:2014-10-05 01:27:21

标签: go

我试图将结构编组到json中。它在struct具有值时有效。但是,当结构没有值时,我无法访问网页:

去:

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无法编组空结构吗?

1 个答案:

答案 0 :(得分: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{}} // 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))
}