How to get binary value from Json object with JsonParserGeneratorRK

Hi,

I would like to get some data from a JSON object in a binary way, so I can send it later through serial port.
I receive the JSON object from a tcp server, and the object includes some strings with Unicode chars.
If I get the value using .valueString() method, the value is transformed to a plain text string that includes unicode formatting chars. How can I get this value without modifying the string?

Let’s say I have next JSON object:

{
	"commands": [
		{
			"cmd": "\u001A\u001B\u0005\u001B"
		},
		{
			"cmd": "\u001C\u001D\u0005\u001B"
		}
	]
}

@rickkas7, how can I access any of “cmd” values without converting them into a plain text string in the commented line in next code?:

#include "JsonParserGeneratorRK.h"


JsonParserStatic<1024, 50> parser;
const char * str = "{\"commands\": [{\"cmd\": \"\\u001A\\u001B\\u0005\\u001B\"},{\"cmd\": \"\\u001C\\u001D\\u0005\\u001B\"}]}";

void runTest();
bool runFlag = true;

// setup() runs once, when the device is first turned on.
void setup() {

 	//open serial port
 	Serial1.begin(115200, SERIAL_8N1);

}

// loop() runs over and over again, as quickly as it can execute.
void loop() {

  if (runFlag){
  
    runTest();
    runFlag = false;
  
  }

}

void runTest() {

  parser.clear();
  parser.addString(str);

  int dataToSend[256];

  //How can I access for example parser[commands][1] and retrieve its data in a binary way (not converted to String), so then I can binary write it to serial?
  //strcpy(txt, ???, ???);

  Serial1.write(*dataToSend);

return;
}

It’s not possible to transfer binary data that way. Not only does the library not support it, but the JSON standard does not support it, and the cloud side does not either. While some binary values < 32 will make it through unchanged, if you happen to insert a byte that is a marker for a 2+ byte Unicode character sequence, differing bad things can happen, but the data is unlikely to make it through.

You should instead encode your binary data as a string, using hex encoding, Base64, or ASCII85 so it can travel safely in JSON data.

3 Likes

Ok, thx.
I will encode/decode the data. Server side is easy (php), but do you know if there are any lib for electron to decode for example Base64 information? If not I will search for a tiny portable one.

I have a library for Base64. It’s Base64RK in the community libraries and the documentation is here:

1 Like

I should have guessed, you have a library for almost everything :smiley:, and all of them are very helpful. Thx.

1 Like