Il mio server Websocket riceverà e dati JSON unmarshal. Questi dati saranno sempre racchiusi in un oggetto con coppie chiave/valore. La stringa di chiavi fungerà da identificatore di valore, dicendo al server Go che tipo di valore è. Sapendo quale tipo di valore, posso quindi passare a JSON unmarshal il valore nel tipo corretto di struct.In parte JSON unmarshal in una mappa in Go
Ogni oggetto json può contenere più coppie chiave/valore.
Esempio JSON:
{
"sendMsg":{"user":"ANisus","msg":"Trying to send a message"},
"say":"Hello"
}
C'è un modo semplice utilizzando il pacchetto "encoding/json"
per fare questo?
package main
import (
"encoding/json"
"fmt"
)
// the struct for the value of a "sendMsg"-command
type sendMsg struct {
user string
msg string
}
// The type for the value of a "say"-command
type say string
func main(){
data := []byte(`{"sendMsg":{"user":"ANisus","msg":"Trying to send a message"},"say":"Hello"}`)
// This won't work because json.MapObject([]byte) doesn't exist
objmap, err := json.MapObject(data)
// This is what I wish the objmap to contain
//var objmap = map[string][]byte {
// "sendMsg": []byte(`{"user":"ANisus","msg":"Trying to send a message"}`),
// "say": []byte(`"hello"`),
//}
fmt.Printf("%v", objmap)
}
Grazie per qualsiasi tipo di suggerimento/aiuto!
Perfetto! Ho perso il modo in cui potresti usare 'RawMessage'. Esattamente quello di cui avevo bisogno. Riguardo 'say', in realtà lo voglio ancora come' json.RawMessage', perché la stringa non è ancora decodificata (avvolgendo '' 'e caratteri di escape' \ n'-caratteri, ecc.), Quindi anche io sarò unmarshal. – ANisus
I Ho risolto la mia risposta per corrispondere a quello che hai fatto. Grazie –
Il tipo dovrebbe essere map [stringa] * json.RawMessage invece perché i metodi Unmarshal/Marshal non sono implementati su json.RawMessage. – albert