2017-06-16 96 views
0

對於下面的代碼,我得到的錯誤:Golang:多結構馬歇爾問題:JSON格式

type A struct{ 
    B_j []B `json:"A"` 
} 
type B struct 
{ 
    X string 
    Y string 

} 

func main() { 
    xmlFile, _ := os.Open("test.xml") 

    b, _ := ioutil.ReadAll(xmlFile) 

    var t root 
    err2 := xml.Unmarshal(b, &rpc) 
    if err2 != nil { 
     fmt.Printf("error: %v", err2) 
     return 
    } 

    for _, name := range t.name{ 
     t := A{B_j : []B{X : name.text, Y: name.type }} // line:#25 

     s, _ := json.MarshalIndent(t,"", " ") 

    os.Stdout.Write(s) 
     } 
} 

# command-line-arguments 
./int2.go:25: undefined: X 
./int2.go:25: cannot use name.Text (type string) as type B in array or slice literal 
./int2.go:25: undefined: Y 
./int2.go:25: cannot use name.type (type string) as type B in array or slice literal 

在我的輸出,我想實現這樣的事情:

{A: {{X:1 ,Y: 2}, {X:2 ,Y: 2}, {X: 2,Y: 2}}} 

結構調用另一個結構來獲取上述模式。

+0

昨天您發佈了有關XML XML unmarshall問題的問題。我已經分析並回答了你的問題。你沒有接受答案,只是你回答「謝謝,這對我來說很愚蠢」,並刪除了SO問題。我建議不要這樣做,這對社區不利。 – jeevatkm

+0

@jeevatkm:這絕對是我的一個無意識的錯誤。現在它回來了。道歉! – Bazinga

+0

謝謝,沒有問題。我只是想把它引起你的注意。順便說一句,我希望答案解決了你的問題。請接受SO中的答案。 – jeevatkm

回答

1

看來你有問題,在這個LINE-

t := A{B_j: []B{X: name.text, Y: name.type }} 

你沒有正確創建切片。嘗試以下各項

t := A{B_j: []B{{X: name.text, Y: name.type}}} 

讓我們做它用靜態值https://play.golang.org/p/a2ZDV8lgWP更好way-

var bj []B 
for _, name := range t.name{ 
    bj = append(bj, B{X: name.text,Y: name.type}) 
} 

t := A{B_j: bj} 
s, _ := json.MarshalIndent(t,"", " ")  
os.Stdout.Write(s) 

樣本程序

注:type是語言的關鍵字,不要使用它作爲變量名。

+0

修正了錯誤,但輸出如下: {A:[{X:1,Y:2}]},{A:[{X:1,Y:2}]},{A: [{X:1,Y:2}]} 我試圖製作類似於: {A:{{X:1,Y:2},{X:2,Y:2},{X :2,Y:2}}} – Bazinga

+0

應該是var bj [] B? – Bazinga

+0

不客氣,加入golang播放鏈接以供參考。 – jeevatkm