JSONCPP binary data

I am trying to use JSON cpp with VS2008.

Can someone tell me if it is possible to pack binary data in JSON format? I read the image file in char* buffer and put it in JSON::Value . But when I try to parse it, I do not find the contents of the buffer in the JSON object.

The code is as follows.

  Json::Value root; Json::Reader reader; Json::StyledWriter writer; int length; char * buffer; ifstream is; is.open ("D:\\test.j2k", ios::binary); // get length of file: is.seekg (0, ios::end); length = is.tellg(); is.seekg (0, ios::beg); // allocate memory: buffer = new char [length]; // read data as a block: is.read (buffer,length); root["sample"] = *buffer; writer.write(root); cout << root; const string rootAsString = root.toStyledString(); cout << rootAsString << endl; 

Since I am new to VC ++, I am not sure if the read / write file to char * buffer is correct / not. Please let me know what is wrong with the code. Thanks.

0
source share
1 answer

You must encode it because JSON is a subset of the javascript structure format, as it appears in javascript source code.

The most commonly used encoding for binary data in JSON is Base64. I use it (in languages ​​other than C ++) to encode images without problems. You just need to prefix the encoded image with data:image/png;base64, (suppose it is png) so that it is automatically decoded in javascript if you set it to src of the image.

EDIT: like in any other language, base64 encoding in C ++ is simple. Here's the library: https://github.com/ReneNyffenegger/development_misc/tree/master/base64

+1
source

Source: https://habr.com/ru/post/1209371/


All Articles