2014-10-05 109 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)) 
}