🎄 Happy Holidays! 🥳
Most of Solace is closed December 24–January 1 so our employees can spend time with their families. We will re-open Thursday, January 2, 2024. Please expect slower response times during this period and open a support ticket for anything needing immediate assistance.
Happy Holidays!
Please note: most of Solace is closed December 25–January 2, and will re-open Tuesday, January 3, 2023.
How to send JSON in Javascript
Hello,
in the example files for Javscript, perticular the TopicPublisher, there is a line of code that defines a message text.
var messageText = 'Sample Message' | |
---|---|
var message = solace.SolclientFactory.createMessage() | |
message.setDestination(solace.SolclientFactory.createTopicDestination(publisher.topicName)) | |
message.setBinaryAttachment(messageText) |
how can i send a JSON format instead of plain text ?
Best Answer
-
Hi @TestUserName, welcome to the Community!
If you want to send some JSON, just do:
message.setBinaryAttachment(JSON.stringify(obj));
Note that
message.setBinaryAttachment(..)
is for just for a plain "raw" binary payload (a BytesMessage). If you want to send a formatted TextMessage in JavaScript, you'd do something like this:var msg = solace.SolclientFactory.createMessage(); var payloadText = JSON.stringify(obj); msg.setSdtContainer(solace.SDTField.create(solace.SDTFieldType.STRING, payloadText)); msg.setDestination(solace.SolclientFactory.createTopic("hello/world"));
Sending a formatted TextMessage is generally better for actual text strings as it is easier to deal with in other APIs, and you don't have to worry about encoding it correctly… e.g. UTF-8 or whatever, especially if your string contains any weird chars. See this thread for more details on that!
5
Answers
-
Hi @TestUserName, welcome to the Community!
If you want to send some JSON, just do:
message.setBinaryAttachment(JSON.stringify(obj));
Note that
message.setBinaryAttachment(..)
is for just for a plain "raw" binary payload (a BytesMessage). If you want to send a formatted TextMessage in JavaScript, you'd do something like this:var msg = solace.SolclientFactory.createMessage(); var payloadText = JSON.stringify(obj); msg.setSdtContainer(solace.SDTField.create(solace.SDTFieldType.STRING, payloadText)); msg.setDestination(solace.SolclientFactory.createTopic("hello/world"));
Sending a formatted TextMessage is generally better for actual text strings as it is easier to deal with in other APIs, and you don't have to worry about encoding it correctly… e.g. UTF-8 or whatever, especially if your string contains any weird chars. See this thread for more details on that!
5