Sure, so groovy has a data type called maps, they're key, value pairs. Other languages call them dictionaries, hashes, etc. So you can do things like thing["key"] = 5
then you've a stored the value 5 into index key . You can then do thing.key
for nicer shorthand to access it as well.
Many of the simple data types of groovy map well to json. That's the {"key": 5}
that you wrote by hand. The { says start a map
and have the index key
with the value 5. Writing json by hand is a pain since you're mixing " in with groovy single quote or double quote for strings, and you get no validation since the language just sees it as text strings.
By writing groovy types, no only is it more readable, but you get the compiler doing syntax checking for you and guaranteeing you get valid json. (within reason)
Walking through the example:
def message_data = [
'type': "auth",
'access_token': "JKV1Qi.LCJhbGciOiJIUzI1NiJ9",
]
This says make a new variable message_data
of type map
and initialize it with 2 elements, type
and access_token
which are both strings. I was lazy and cutting and pasting, but could/should have changed to the "auth"
to 'auth'
to not only be consistent, but because were aren't doing any variable expansion.
def json = new groovy.json.JsonOutput().toJson(message_data)
This (via a round about route) calls the library function toJson
to convert a groovy map/type/etc into json. The return value is a string of json. I just cut & paste the code above from somewhere, but as I read the docs (link lower down) I realized it's a bit dumb and you could write:
def json = groovy.json.JsonOutput.toJson(obj)
Groovy isn't a language I'm all the familiar with tbh, and like all things there's a but of junk out there.
This this line sends the string returned from above call.
interfaces.webSocket.sendMessage(json)
Docs for the json parser and producer are at: The Apache Groovy programming language - Parsing and producing JSON