JSON全稱為JavaScript ObjectNotation,它是一種輕量級的數據交換格式,易於閱讀、編寫、解析。jsoncpp是c++解析JSON串常用的解析庫之一。
jsoncpp中主要的類:
Json::Value:可以表示所有支持的類型,如:int , double ,string , object, array等。其包含節點的類型判斷(isNull,isBool,isInt,isArray,isMember,isValidIndex等),類型獲取(type),類型轉換(asInt,asString等),節點獲取(get,[]),節點比較(重載<,<=,>,>=,==,!=),節點操作(compare,swap,removeMember,removeindex,append等)等函數。
Json::Reader:將文件流或字符串創解析到Json::Value中,主要使用parse函數。Json::Reader的構造函數還允許用戶使用特性Features來自定義Json的嚴格等級。
Json::Writer:與JsonReader相反,將Json::Value轉換成字符串流等,Writer類是一個純虛類,並不能直接使用。在此我們使用 Json::Writer 的子類:Json::FastWriter(將數據寫入一行,沒有格式),Json::StyledWriter(按json格式化輸出,易於閱讀)。
Json::Reader可以通過對Json源目標進行解析,得到一個解析好了的Json::Value,通常字符串或者文件輸入流可以作為源目標。
如下Json文件example.json:
-
{
-
"encoding" : "UTF-8",
-
"plug-ins" : [
-
"python",
-
"c++",
-
"ruby"
-
],
-
"indent" : { "length" : 3, "use_space": true }
-
"tab":null
-
}
使用Json::Reader對Json文件進行解析:
-
Json::Value root;
-
Json::Reader reader;
-
std::ifstream ifs("example.json");//open file example.json
-
-
if(!reader.parse(ifs, root)){
-
// fail to parse
-
}
-
else{
-
// success
-
std::cout <<root["encoding"].asString()<<endl;
-
std::cout<<root["indent"]["length"].asInt()<<endl;
-
}
使用Json::Reader對字符串進行解析:
-
Json::Value root;
-
Json::Reader reader;
-
const char* s = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";
-
if(!reader.parse(s, root)){
-
// "parse fail";
-
}
-
else{
-
std::cout << root["uploadid"].asString();//print "UP000000"
-
}
Json::Writer 和 Json::Reader相反,是把Json::Value對象寫到string對象中,而且Json::Writer是個抽象類,被兩個子類Json::FastWriter和Json::StyledWriter繼承。
簡單來說FastWriter就是無格式的寫入,這樣的Json看起來很亂沒有格式,而StyledWriter就是帶有格式的寫入,看起來會比較友好。
-
Json::Value root;
-
Json::Reader reader;
-
Json::FastWriter fwriter;
-
Json::StyledWriter swriter;
-
-
if(! reader.parse("example.json", root)){
-
// parse fail
-
return 0;
-
}
-
std::string str = fwriter(root);
-
std::ofstream ofs("example_fast_writer.json");
-
ofs << str;
-
ofs.close();
-
-
str = swriter(root);
-
ofs.open("example_styled_writer.json");
-
ofs << str;
-
ofs.close();
-
-
結果1:example_styled_writer.json:
-
{
-
"encoding" : "UTF-8",
-
"plug-ins" : [
-
"python",
-
"c++",
-
"ruby"
-
],
-
"indent" : { "length" : 3, "use_space": true }
-
"tab":null
-
}
-
-
結果2:example_fast_writer.json:
-
{"encoding" : "UTF-8","plug-ins" : ["python","c++","ruby"],"indent" : { "length" : 3, "use_space": true}}
Json其它函數的應用:
1、判斷KEY值是否存在:
-
if(root.isMember("encoding")){
-
std::cout <<"encoding is a member"<<std::endl;
-
}
-
else{
-
std::cout<<"encoding is not a member"<<std::endl;
-
}
2、判斷Value是否為null:
if(root["tab"].isNull()){
std::cout << "isNull" <<std::endl;//print isNull
}
完整例子使用舉例來自於CSDN下載網友的程序:
源碼下載地址:http://download.csdn.net/download/woniu211111/9966907
-
/********************************************************
-
Copyright (C), 2016-2017,
-
FileName: main
-
Author: woniu201
-
Email: wangpengfei.201@163.com
-
Created: 2017/09/06
-
Description:use jsoncpp src , not use dll, but i also provide dll and lib.
-
********************************************************/
-
-
#include "stdio.h"
-
#include <string>
-
#include "jsoncpp/json.h"
-
-
using namespace std;
-
-
/************************************
-
@ Brief: read file
-
@ Author: woniu201
-
@ Created: 2017/09/06
-
@ Return: file data
-
************************************/
-
char *getfileAll(char *fname)
-
{
-
FILE *fp;
-
char *str;
-
char txt[1000];
-
int filesize;
-
if ((fp=fopen(fname,"r"))==NULL){
-
printf("open file %s fail \n",fname);
-
return NULL;
-
}
-
-
/*
-
獲取文件的大小
-
ftell函數功能:得到流式文件的當前讀寫位置,其返回值是當前讀寫位置偏離文件頭部的字節數.
-
*/
-
fseek(fp,0,SEEK_END);
-
filesize = ftell(fp);
-
-
str=(char *)malloc(filesize);
-
str[0]=0;
-
-
rewind(fp);
-
while((fgets(txt,1000,fp))!=NULL){
-
strcat(str,txt);
-
}
-
fclose(fp);
-
return str;
-
}
-
-
/************************************
-
@ Brief: write file
-
@ Author: woniu201
-
@ Created: 2017/09/06
-
@ Return:
-
************************************/
-
int writefileAll(char* fname,const char* data)
-
{
-
FILE *fp;
-
if ((fp=fopen(fname, "w")) == NULL)
-
{
-
printf("open file %s fail \n", fname);
-
return 1;
-
}
-
-
fprintf(fp, "%s", data);
-
fclose(fp);
-
-
return 0;
-
}
-
-
/************************************
-
@ Brief: parse json data
-
@ Author: woniu201
-
@ Created: 2017/09/06
-
@ Return:
-
************************************/
-
int parseJSON(const char* jsonstr)
-
{
-
Json::Reader reader;
-
Json::Value resp;
-
-
if (!reader.parse(jsonstr, resp, false))
-
{
-
printf("bad json format!\n");
-
return 1;
-
}
-
int result = resp["Result"].asInt();
-
string resultMessage = resp["ResultMessage"].asString();
-
printf("Result=%d; ResultMessage=%s\n", result, resultMessage.c_str());
-
-
Json::Value & resultValue = resp["ResultValue"];
-
for (int i=0; i <resultValue.size(); i++)
-
{
-
Json::Value subJson = resultValue[i];
-
string cpuRatio = subJson["cpuRatio"].asString();
-
string serverIp = subJson["serverIp"].asString();
-
string conNum = subJson["conNum"].asString();
-
string websocketPort = subJson["websocketPort"].asString();
-
string mqttPort = subJson["mqttPort"].asString();
-
string ts = subJson["TS"].asString();
-
-
printf("cpuRatio=%s; serverIp=%s; conNum=%s; websocketPort=%s; mqttPort=%s; ts=%s\n",cpuRatio.c_str(), serverIp.c_str(),
-
conNum.c_str(), websocketPort.c_str(), mqttPort.c_str(), ts.c_str());
-
}
-
return 0;
-
}
-
-
/************************************
-
@ Brief: create json data
-
@ Author: woniu201
-
@ Created: 2017/09/06
-
@ Return:
-
************************************/
-
int createJSON()
-
{
-
Json::Value req;
-
req["Result"] = 1;
-
req["ResultMessage"] = "200";
-
-
Json::Value object1;
-
object1["cpuRatio"] = "4.04";
-
object1["serverIp"] = "42.159.116.104";
-
object1["conNum"] = "1";
-
object1["websocketPort"] = "0";
-
object1["mqttPort"] = "8883";
-
object1["TS"] = "1504665880572";
-
Json::Value object2;
-
object2["cpuRatio"] = "2.04";
-
object2["serverIp"] = "42.159.122.251";
-
object2["conNum"] = "2";
-
object2["websocketPort"] = "0";
-
object2["mqttPort"] = "8883";
-
object2["TS"] = "1504665896981";
-
-
Json::Value jarray;
-
jarray.append(object1);
-
jarray.append(object2);
-
-
req["ResultValue"] = jarray;
-
-
Json::FastWriter writer;
-
string jsonstr = writer.write(req);
-
-
printf("%s\n", jsonstr.c_str());
-
-
writefileAll("createJson.json", jsonstr.c_str());
-
return 0;
-
}
-
-
int main()
-
{
-
/*讀取Json串,解析Json串*/
-
char* json = getfileAll("parseJson.json");
-
parseJSON(json);
-
printf("===============================\n");
-
-
/*組裝Json串*/
-
createJSON();
-
-
getchar();
-
return 1;
-
}
參考:
http://open-source-parsers.github.io/jsoncpp-docs/doxygen/index.html
