/ / Come rimuovere Unmarshal dall'array json? - array, json, go, slice

Come Unmarshal l'array json? - array, json, go, slice

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 № 1

Prima 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:

  1. Volevi decodificare in un oggetto. In questo caso, basta dichiarare s come un Serverslice. Ecco una versione del tuo programma che apporta quella modifica: http://play.golang.org/p/zgyr_vnn-_

  2. 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