二进制数据JSONCPP [英] Binary data JSONCPP

查看:2043
本文介绍了二进制数据JSONCPP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用JSON cpp与VS2008。



任何人都可以告诉我是否可能将二进制数据打包成JSON格式?我正在读一个图像文件到 char * buffer ,并把它放在 JSON :: Value 。但是当我尝试解析它时,我在JSON对象中找不到缓冲区内容。



代码如下。

  Json :: Value root; 
Json :: Reader reader;
Json :: StyledWriter writer;
int length;
char * buffer;
ifstream is;
is.open(D:\\test.j2k,ios :: binary);

//获取文件长度:
is.seekg(0,ios :: end);
length = is.tellg();
is.seekg(0,ios :: beg);

//分配内存:
buffer = new char [length];

//以块的形式读取数据:
is.read(buffer,length);
root [sample] = * buffer;
writer.write(root);
cout<<根;
const string rootAsString = root.toStyledString();
cout<< rootAsString<< endl;

由于我是VC ++的新手,我不知道读取图像文件到char *正确错误。请让我知道代码的错误。感谢。

解决方案

您必须对其进行编码,因为JSON是JavaScript源代码中出现的JavaScript结构格式的子集。 p>

JSON中二进制数据最常用的编码是Base64。我使用它(在其他语言,而不是c ++)编码图像没有问题。你只需要在编码的图像前面加上 data:image / png; base64,(假设它是png),让它在javascript中自动解码,如果你设置为src一个图像。



编辑:与任何其他语言一样,C64中的base64编码很容易。这里有一个图书馆: https://github.com/ReneNyffenegger/development_misc/tree/master/base64


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.

解决方案

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

这篇关于二进制数据JSONCPP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆