unmarshalling arbitrary data

You can unmarshall bottom half in json.RawMessage first, something like

package main

import (
    "encoding/json"
    "fmt"
)

type Message struct {
    Code    int
    Payload json.RawMessage // delay parsing until we know the code
}
type Range struct {
    Start int
    End   int
}
type User struct {
    ID   int
    Pass int
}

func MyUnmarshall(m []byte) {
    var message Message
    var payload interface{}
    json.Unmarshal(m, &message) // delay parsing until we know the color space
    switch message.Code {
    case 3:
        payload = new(User)
    case 4:
        payload = new(Range)
    }
    json.Unmarshal(message.Payload, payload) //err check ommited for readability
    fmt.Printf("\n%v%+v", message.Code, payload) //do something with data
}

func main() {
    json := []byte(`{"Code": 4, "Payload": {"Start": 1, "End": 10}}`)
    MyUnmarshall(json)
    json = []byte(`{"Code": 3, "Payload": {"ID": 1, "Pass": 1234}}`)
    MyUnmarshall(json)
}

Leave a Comment