C'è qualcosa di sbagliato quando ho unmarshal dell'array json.
Come lo correggo? il codice è:http://play.golang.org/p/AtU9q8Hlye
package main
import (
"encoding/json"
"fmt"
)
type Server struct {
ServerName string
ServerIP string
}
type Serverslice struct {
Name string
Servers []Server
}
func main() {
var s []Serverslice
str := `{"name":"dxh","servers":[{"serverName":"VPN0","serverIP":"127.0.0.1"},{"serverName":"Beijing_VPN","serverIP":"127.0.0.2"}],
"name":"dxh1,"servers":[{"serverName":"VPN1","serverIP":"127.0.0.1"},{"serverName":"Beijing_VPN","serverIP":"127.0.0.2"}]}`
json.Unmarshal([]byte(str), &s) //the wrong line.....................
fmt.Println(len(s))
}
risposte:
4 per risposta № 1Prima di tutto, stai ignorando il valore restituito dall'errore json.Unmarshal
. Probabilmente vuoi qualcosa come:
if err := json.Unmarshal([]byte(str), &s); err != nil {
log.Fatalln(err)
}
Con questa modifica, possiamo vedere che i tuoi dati JSON non sono validi: invalid character "s" after object key:value pair
. C'è una citazione mancante alla fine di "dxh1
sulla seconda riga.
Risolvendo quell'errore e rieseguendo il programma otterrai un errore diverso: json: cannot unmarshal object into Go value of type []main.Serverslice
. Ci sono due possibili problemi qui:
Volevi decodificare in un oggetto. In questo caso, basta dichiarare
s
come unServerslice
. Ecco una versione del tuo programma che apporta quella modifica: http://play.golang.org/p/zgyr_vnn-_Il tuo JSON dovrebbe essere un array (possibile, dal momento che sembra avere le chiavi duplicate). Ecco una versione aggiornata con JSON modificata per fornire un array: http://play.golang.org/p/Wl6kUaivEm