jsoncpp小例項
1:安裝json庫:
sudo apt-get install libjsoncpp0 libjsoncpp-dev
2:編譯方式:編譯時加上庫路徑
g++ my_test_jsoncpp.cpp -L/usr/lib/x86_64-linux-gnu -ljsoncpp -o my_test
3:json資料解析:
#include<jsoncpp/json/json.h>
int main()
{
const char* s = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\" ,\"files\": \"\"}";
Json::Reader reader;
Json::Value root;
if (!reader.parse(s, root))
{
return -1;
}
std::string name = root["uploadid"].asString();
int age = root["code"].asInt();
std::cout<<name<<std::endl;
std::cout<<age<<std::endl;
return 0;
}
結果如下:
4:json資料封裝(FastWriter 方式)
#include<jsoncpp/json/json.h>
int main()
{
Json::Reader reader;
Json::Value root;
Json::Value root1;
Json::FastWriter fwrite;
Json::StyledWriter swriter;
root1["name"] = "hello";
root1["age"] = 100;
root.append(root1);
std::string json_str=fwrite.write(root1);
std::string str = fwrite.write(root);
std::cout<<json_str<<std::endl;
std::cout<<str<<std::endl;
return 0
}
輸出結果如下:
root1 被轉化為json物件資料格式
root 被轉化為json陣列資料格式