Some client libraries provide helpers to send structured data while others depend on the application to perform any encoding and decoding and just take byte arrays for sending. The following example shows how to send JSON but this could easily be altered to send a protocol buffer, YAML or some other format. JSON is a text format so we also have to encode the string in most languages to bytes. We are using UTF-8, the JSON standard encoding.
Take a simple stock ticker that sends the symbol and price of each stock:
classStockForJsonPub {publicString symbol;publicfloat price;}publicclassPublishJSON {publicstaticvoidmain(String[] args) {try {Connection nc =Nats.connect("nats://demo.nats.io:4222");// Create the data objectStockForJsonPub stk =newStockForJsonPub();stk.symbol="GOOG";stk.price=1200;// use Gson to encode the object to JSONGsonBuilder builder =newGsonBuilder();Gson gson =builder.create();String json =gson.toJson(stk);// Publish the messagenc.publish("updates",json.getBytes(StandardCharsets.UTF_8));// Make sure the message goes through before we closenc.flush(Duration.ZERO);nc.close(); } catch (Exception e) {e.printStackTrace(); } }}
// dotnet add package NATS.NetusingNATS.Net;awaitusingvar client =newNatsClient();usingvar cts =newCancellationTokenSource();Task process =Task.Run(async () =>{ // Let's deserialize the message as a UTF-8 string to see // the published serialized output in the consoleawaitforeach (var msg inclient.SubscribeAsync<string>("updates", cancellationToken:cts.Token)) {Console.WriteLine($"Received: {msg.Data}"); }});// Wait for the subscription task to be readyawaitTask.Delay(1000);var stock =newStock { Symbol ="MSFT", Price =123.45 };// The default serializer uses System.Text.Json to serialize the objectawaitclient.PublishAsync<Stock>("updates", stock);// Define the objectpublicrecordStock {publicstring Symbol { get; set; }publicdouble Price { get; set; }}// Output:// Received: {"Symbol":"MSFT","Price":123.45}