francoispqt / gojay

high performance JSON encoder/decoder with stream API for Golang
MIT License
2.11k stars 112 forks source link

How to Unmarshal to struct of uncertain type #95

Closed wardbradt closed 5 years ago

wardbradt commented 5 years ago

If I have a stream of JSON messages coming in as []byte, with some messages having "foo" as a key and some with "bar" as key, how can I Unmarshal the "foo" messages into one type of struct and the "bar" messages into another?

type FooMessage struct {
    foo  int
    ... other fields ...
}

type BarMessage struct {
    bar  int
    ... other fields ...
}

Given the example in the README:

func main() {
    ...
    ws, err := websocket.Dial(url, "", origin)
    streamChan := ChannelStream(make(chan *user))
    dec := gojay.Stream.BorrowDecoder(ws)
    go dec.DecodeStream(streamChan)
}

I believe the logic needs to be in UnmarshalStream. However, I am not sure how to determine what value of what type should be passed to dec.Object.

Note: This is a simplified example, I need to solve this for >5 types of messages.

wardbradt commented 5 years ago

Closed because after looking at gojay's code I have found that this behavior is not yet available in the library. I think it would be a non-negligible task to extend the functionality of the library to do this as the architecture seems to be not designed for such a use case.