0

I am trying to use JSON cpp with VS2008.

Can anyone tell me is it possible to pack binary data into JSON format? I am reading a image file into char* buffer, and putting it in JSON::Value. But when i try to parse it, I don't find the buffer contents in the JSON object.

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 whether reading a image file to char * buffer is right/wrong. Please let me know whats wrong with the code. Thanks.

Sga
  • 3,608
  • 2
  • 36
  • 47
Pavan
  • 1,023
  • 2
  • 12
  • 25

1 Answers1

2

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

The most frequently used encoding for binary data in JSON is Base64. I use it (in other languages than c++) for encoding images without problems. You simply have to prefix the encoded image with data:image/png;base64, (supposing it's png) to have it automatically decoded in javascript if you set this to the src of an image.

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

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • can you explain in terms of above code? where I have made mistake? – Pavan May 30 '12 at 08:10
  • You put the content of your file in your value and you ask the StyledWriter to encode it. How is it supposed to know it should add the prefix I propose and encode it in base64 ? – Denys Séguret May 30 '12 at 08:14