用c ++解码json

时间:2013-10-28 06:48:05

标签: c++ json

我已经在MySQL数据库中以json格式保存了我的数据。我想用c ++解码它。我使用SimpleJSON对其进行编码,但我无法提取它。我的数据库格式是:

 [[{"x":36},{"y":0},{"value":0.47873455286026}],
[{"x":68},{"y":0},{"value":0.00944233685731888}],
[{"x":35},{"y":0},{"value":0.00944233685731888}],
[{"x":206},{"y":0},{"value":0.00944233685731888}]]

保存在1列中。我将此值作为数据库的字符串。我怎么解码呢?我用来编码的代码是:

  JSONArray array;
     for (int j = 0;j<bb.rows;j++ ){
         JSONArray v;
        JSONObject x,y,value,result;

        x[L"x"]=new JSONValue ((double) (bb.at<double>(j,0)));
        y[L"y"]=new JSONValue ((double)(0));
        value[L"value"]=new JSONValue(bb.at<double>(j,1));

         v.push_back(new JSONValue(x));
        v.push_back(new JSONValue(y));
        v.push_back(new JSONValue(value));
        array.push_back(new JSONValue(v));
    }

我按照这个链接。 https://github.com/MJPA/SimpleJSON

1 个答案:

答案 0 :(得分:2)

#include "JSON.h"
#include "iostream"

int main() {

    char *json_string = "[[{\"x\":36},{\"y\":0},{\"value\":0.47873455286026}], \
        [{\"x\":68},{\"y\":0},{\"value\":0.00944233685731888}], \
        [{\"x\":35},{\"y\":0},{\"value\":0.00944233685731888}], \
        [{\"x\":206},{\"y\":0},{\"value\":0.00944233685731888}]]";

    JSONValue *data = JSON::Parse(json_string);

    for( size_t i=0; i<data->CountChildren(); ++i ) {
        JSONValue *row = data->Child(i); 
        std::cout << "x = " << row->Child(0)->Child(L"x")->AsNumber() << std::endl;
        std::cout << "y = " << row->Child(1)->Child(L"y")->AsNumber() << std::endl;
        std::cout << "value = " << row->Child(2)->Child(L"value")->AsNumber() << std::endl;
        std::cout << std::endl;
    }

    return 0;
}

以下是在线测试的代码 - http://ideone.com/wBRZfI(请参阅最后的代码,因为整个SimpleJSON源都粘贴在那里)