본문 바로가기

카테고리 없음

c++ json parser example

json lib parser

jsoncpp.tar.gz
0.05MB

/*
g++ ./test.cc ./jsoncpp/jsoncpp.cpp -I./jsoncpp -L./jsoncpp -ljsoncpp
*/
#include "json/json.h"
#include <string>
#include <iostream>
#include <stdio.h>
#define JSON_FILE "sample.json"

bool ReadFromFile(const char* filename, char* buffer, int len)
{
FILE* r = fopen(filename, "rb");
if (NULL == r)
return false;
size_t fileSize = fread(buffer, 1, len, r);
fclose(r);
return true;
}
/*
{
"title": "Get Request",
"action": "get",
"type": "object",
"path": "Vehicle.xx.xx.xx,
"requestId": "1"
}
}
*/
#define ARGS_INT 1
int main(int argc, char* argv[]) {
std::cout << "args "<<argv[1]<<std::endl;
if(argv[1] == "1") {
const int BufferLength = 102400;
char readBuffer[BufferLength] = {0,};
if (false == ReadFromFile(JSON_FILE, readBuffer, BufferLength)) {
return 0;
}
std::cout << "read file \n" << readBuffer;
std::string config_doc = readBuffer;
Json::Value root;
Json::Reader reader;


bool parsingSuccessful = reader.parse( config_doc, root );
if ( !parsingSuccessful ) {
std::cout << "Failed to parse configuration\n"
<< reader.getFormatedErrorMessages();
return 0;
}

Json::Value title = root["title"];
std::cout << __func__ << " " <<" " << title.asString() <<std::endl;
 
std::cout << "name : " << root["action"].asString() << std::endl;
std::cout << "type : " << root["type"].asString() << std::endl;
std::cout << "path : " << root["path"].asString() << std::endl;
std::cout << "requestId : " << root["requestId"].asString() << std::endl;

}else{
std::string str;
Json::Value root;
root["name"] = "Lee";
root["age"] = 28;
root["hasCar"] = true;

Json::Value items;
items.append("nootbook");
items.append("iphone");
items.append("apple-watch");
root["items"] = items;

Json::Value friends;
Json::Value park;
Json::Value tom,jane;
 
tom["name"] = "Park";
tom["age"] = 30;
Json::Value kim;
jane["name"] = "Kim";
jane["age"] = 25;
friends.append(park);
friends.append(kim);
root["friends"] = friends;
 
Json::StyledWriter writer;
str = writer.write(root);
std::cout << str << std::endl << std::endl;
}
return 0;
}