This page has moved to

Click here if you are not redirected.

Sending Structured Data

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:

nc, err := nats.Connect("")
if err != nil {
defer nc.Close()

ec, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
if err != nil {
defer ec.Close()

// Define the object
type stock struct {
	Symbol string
	Price  int

// Publish the message
if err := ec.Publish("updates", &stock{Symbol: "GOOG", Price: 1200}); err != nil {
class StockForJsonPub {
    public String symbol;
    public float price;

public class PublishJSON {
    public static void main(String[] args) {
        try {
            Connection nc = Nats.connect("nats://");

            // Create the data object
            StockForJsonPub stk = new StockForJsonPub();

            // use Gson to encode the object to JSON
            GsonBuilder builder = new GsonBuilder();
            Gson gson = builder.create();
            String json = gson.toJson(stk);

            // Publish the message
            nc.publish("updates", json.getBytes(StandardCharsets.UTF_8));

            // Make sure the message goes through before we close
        } catch (Exception e) {
let nc = NATS.connect({url: "nats://", json: true});
nc.publish('updates', {ticker: 'GOOG', price: 1200});
nc = NATS()

await nc.connect(servers=["nats://"])

await nc.publish("updates", json.dumps({"symbol": "GOOG", "price": 1200 }).encode())

require 'nats/client'
require 'json'

NATS.start(servers:["nats://"]) do |nc|
  nc.publish("updates", {"symbol": "GOOG", "price": 1200}.to_json)
let nc = await connect({
    url: "nats://",
    payload: Payload.JSON

nc.publish('updates', {ticker: 'GOOG', price: 1200});

results matching ""

    No results matching ""