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(); } }}