[Gambas-user] Encode JSON form a collection within a collection?
Benoît Minisini
benoit.minisini at gambas-basic.org
Thu Feb 1 15:00:57 CET 2024
Le 01/02/2024 à 05:06, Admin a écrit :
> Greetings!
>
> I decided to make an SMS notifications for myself, chose a provider and
> read the API documentation. It's pretty straight-forward, they just want
> to recieve a JSON push like this:
>
> {
> "destination": "phone",
> "originator": "alpha name",
> "body": "message text",
> "msisdn": "972000000",
> "reference": "ext_id_16",
> "validity": "1",
> "tariff": "0",
> "callback_url": "your_url"
> }
>
> So I wrote a code:
>
> Public Sub SendSMS(sText As String, num As String)
> Dim hClient As New HttpClient
> Dim restapi As New Collection
> Dim headers As New String[]
>
> headers.Add("X-API-KEY: whatevermykeyis")
> headers.Add("accept: application/json")
>
> restapi.Add("phone", "destination")
> restapi.Add("Me", "originator")
> restapi.Add(sText, "body")
> restapi.Add(num, "msisdn")
> restapi.Add("ext_id_" & Int(Rnd(1, 9)) & CInt(Now), "reference")
>
> hClient.URL = "https://api.myprovider.url/sms/create"
> hClient.Post("application/json", JSON.Encode(restapi), headers,
> "~/sms.log")
> End
>
> And it works, no problem. I was happy till I had to send the same SMS to
> more (a lot more) people. I can just pass 'num' for each number I want
> and send separate SMSes, which I do, but it's expensive. The prodiver
> can send up to 50 SMSes for the price of just one if I use another push
> request:
>
> {
> "validity": "1",
> "tariff": "0",
> "destination": "phones",
> "originator": "alpha_name",
> "body": "message text",
> "phones":
> [
> {
> "msisdn": "972000000",
> "reference": "ext_id_17"
> },
> {
> "msisdn": "972000001",
> "reference": "ext_id_18"
> }
> ],
> "callback_url": "your_url"
> }
>
>
> And here I'm a bit stuck. How do I encode an array, a collection maybe,
> into a JSON which already is a collection?
>
>
> Dmitry.
>
You just create the same structure in Gambas as in JSON, a JSON array
being a Variant[] (or any other array), and a JSON object being a
collection.
So, for example:
--8<------------------------------------------------------------
Dim vArg As Variant
vArg = [
"validity": 1,
"tariff": 0,
"destination": "phones",
"originator": "alpha_name",
"body": "message text",
"phones": [
[
"msisgn": "972000000",
"reference": "ext_id_17"
],
[
"msisdn": "972000001",
"reference": "ext_id_18"
]
],
"callback_url": "your_url"
]
hClient.URL = "https://api.myprovider.url/sms/create"
hClient.Post("application/json", JSON.Encode(vArg), ...)
--8<------------------------------------------------------------
Regards,
--
Benoît Minisini.
More information about the User
mailing list