2014-10-05 108 views
0

我试图将一个结构编组为json。它在结构体具有值时起作用。不过,我无法访问网页时的结构有没有价值:转到:元帅空结构到json

转到:

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不能元帅空结构?

+0

什么错误?你明确地忽略了错误。它可能有助于检查它。另外,{[]}在Go中无效。 – Logiraptor 2014-10-05 01:37:01

回答

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)) 
}