Structured Data

    For example, to receive JSON you could do:

    {% tabs %} {% tab title=”Go” %}

    {% endtab %}

    1. public String symbol;
    2. public float price;
    3. public String toString() {
    4. return symbol + " is at " + price;
    5. }
    6. }
    7. public class SubscribeJSON {
    8. public static void main(String[] args) {
    9. try {
    10. Connection nc = Nats.connect("nats://demo.nats.io:4222");
    11. // Use a latch to wait for 10 messages to arrive
    12. CountDownLatch latch = new CountDownLatch(10);
    13. // Create a dispatcher and inline message handler
    14. Dispatcher d = nc.createDispatcher((msg) -> {
    15. Gson gson = new Gson();
    16. StockForJsonSub stk = gson.fromJson(json, StockForJsonSub.class);
    17. // Use the object
    18. System.out.println(stk);
    19. latch.countDown();
    20. });
    21. // Subscribe
    22. d.subscribe("updates");
    23. // Wait for a message to come in
    24. latch.await();
    25. // Close the connection
    26. nc.close();
    27. } catch (Exception e) {
    28. e.printStackTrace();
    29. }
    30. }

    {% endtab %}

    {% tab title=”JavaScript” %}

    {% endtab %}

    1. import json
    2. from nats.aio.client import Client as NATS
    3. from nats.aio.errors import ErrTimeout
    4. async def run(loop):
    5. nc = NATS()
    6. await nc.connect(servers=["nats://127.0.0.1:4222"], loop=loop)
    7. async def message_handler(msg):
    8. data = json.loads(msg.data.decode())
    9. print(data)
    10. sid = await nc.subscribe("updates", cb=message_handler)
    11. await nc.flush()
    12. await nc.auto_unsubscribe(sid, 2)
    13. await nc.publish("updates", json.dumps({"symbol": "GOOG", "price": 1200 }).encode())
    14. await asyncio.sleep(1, loop=loop)
    15. await nc.close()

    {% endtab %}

    {% tab title=”Ruby” %}

    {% endtab %}

      {% endtab %} {% endtabs %}