Reputation: 1086
Is there a way to marshall JSON data in such a way that it can be unmarshalled in parts / sections?
Let's say that the top half of data is a "code" which would signal what to do with the bottom half ... such as unmarshall the bottom half into a specific struct depending on the "code".
There are two structs that may be sent as the bottom half ...
type Range Struct {
Start int
End int
}
type User struct {
ID int
Pass int
}
PSEUDO CODE EXAMPLE
It may look like this ...
message := &Message{
Code: 4,
&Range {
Start: 1,
End: 10,
}
}
Itt may look like this ...
message := &Message{
Code: 3,
&User {
ID: 1,
Pass: 1234,
}
}
So, when unmarshalling that data I could ...
// get code from top half
m := Message{}
err = json.UnMarshallTopHalf(byteArray, &m)
if m.Code == 4 {
// ok, the code was four, lets unmarshall into type Range
r := Range{}
json.UnmarshalBottomHalf(byteArray, &r)
}
I have looked at JSON & Go to learn how to marshall and unmarshall defined structs. I can do this, but I cannot figure out a way for arbitrary data as in the example above ...
Upvotes: 0
Views: 903
Reputation: 8490
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)
}
Upvotes: 1
Reputation:
type Message struct {
Code int `json:"cc"`
Range *Range `json:"vvv,omitempty"`
User *User `json:"fff,omitempty"`
}
then given code == x, use range, if Y, use User.
Upvotes: 1