Hi all!
I'm working with a very weird websocket connection. Instead of having objects with keys which can be mapped to structs they send array with all dynamic types.
example:
[
27291,
[
1508101980000,
5510,
5506.1,
5510.3,
5506,
5.71021852
]
]
another example:
[
70,
[
5511,
2,
-0.94000001
]
]
another one:
[
0,
"pb",
[]
]
This couldn't be mapped to any concrete type without using reflection. I've been using the bytes
package to clean the byte arrays retrieved and split to get the right data. As the endpoints I use from the api grow this becomes really cumbersome. I was wondering if there is an more efficient way, without reflection.
Thanks in advance!
评论:
tv64738:
forfunc:
[]json.RawMessage
, and perhapsjson.Decoder.Token
.How will you know what types the items will be? For example, does the first item dictate the types of the rest? If so, http://eagain.net/articles/go-dynamic-json/ and http://eagain.net/articles/go-json-array-to-struct/ should show you the way.
sgmansfield:Thanks!! Json. Decoder. Token is exactly what I needed
sh41:FWIW I use this in a project and it works well. I recommend it as well.
One caveat, you have to remember to replace the remainder of the buffer at the front of the input reader after you're done reading the json. The parser has its own buffer.
forfunc:Definitely consider using https://godoc.org/encoding/json#Decoder.Token, as /u/tv64738 suggested:
itsmontoya:That looks as the solution I needed!! Thank you
ericzhill:You might be able to do it with jsoon, but it's no where near production-ready. If you decide to use it and encounter bugs, submit a github issue
Easy. Use the existing json grammar with antlr. Have antlr generate your parser code, and write event handlers to handle the begin/end events as the string is parsed.
https://github.com/antlr/grammars-v4/blob/master/json/JSON.g4
It's a bit of a learning curve and not terribly well documented, but it's lightning fast and rock solid stable.
