使用jsoncpp解析生成json

时间:2023-11-15 14:31:26

此站点下载jsoncpp(https://sourceforge.net/projects/jsoncpp/这个站点的版本较旧)

在电脑上安装Python,运行amalgamate.py,生成的dist目录中包含了我们需要的源文件和头文件

以下是使用jsoncpp解析与生成json的示例代码,

其中json_text.txt的内容为(关于此json数据的来源可参考此站点

{
"face":
[
{
"attribute":
{
"age":27,
"gender":"Male",
"lefteye_opendegree":43,
"mouth_opendegree":2,
"pose":
{
"raise":-21,
"tilting":-2,
"turn":4
},
"righteye_opendegree":47
},
"face_id":"83e3edac3d5d49579089d3ee043d41ec",
"position":
{
"center":{"x":179,"y":50},
"eye_left":{"x":206,"y":78},
"eye_right":{"x":248,"y":78},
"height":94,"width":94
},
"tag":""
}
],
"img_height":500,
"img_id":"030-3aff983ea4ea5a35f89ae6",
"img_width":350,
"res_code":"0000",
"url":"http://e.hiphotos.baidu.com/baike/pic/item/9345d688d43f879428d347b3d81b0ef41bd53a7a.jpg"
}

jsoncpp_parse_test.cpp

#include <iostream>
#include <fstream>
#include "jsoncpp/json.h"
int main()
{
using namespace std;
using namespace Json;
ifstream ifs("json_text.txt");
if (ifs)
{
string line, jsonStr;
while (getline(ifs, line))
jsonStr.append(line);
CharReader *reader = CharReaderBuilder().newCharReader();
Value root;
JSONCPP_STRING errs;
if (reader->parse(jsonStr.c_str(), jsonStr.c_str() + jsonStr.size(), &root, &errs))
{
auto faceId = root["face"][]["face_id"].asString();
auto imgWidth = root["img_width"].asInt();
auto imgHeight = root["img_height"].asInt();
auto resCode = root["res_code"].asString();
auto url = root["url"].asString();
cout << "face_id:\t" << faceId << endl;
cout << "img_width:\t" << imgWidth << endl;
cout << "img_height:\t" << imgHeight << endl;
cout << "res_code:\t" << resCode << endl;
cout << "url:\t\t" << url << endl;
}
else
cout << errs << endl;
delete reader;
}
return ;
}

jsoncpp_generate_test.cpp

#include <iostream>
#include <memory>
#include "jsoncpp/json.h"
int main()
{
std::unique_ptr<Json::StreamWriter> writer(Json::StreamWriterBuilder().newStreamWriter());
Json::Value array, element;
element["face_id"] = "a9cebf8d5ae6fff514d8d2d8e07fa55b";
element["similarity"] = ;
element["img_id"] = "12.jpg";
element["people_name"] = "张艺谋";
array["result"].append(element);
element["face_id"] = "7f2de0e85bede3171c839d0dcabd849f";
element["similarity"] = 55.379097;
element["img_id"] = "6.jpg";
element["people_name"] = "曾国藩";
array["result"].append(element);
element["face_id"] = "40ebb31e8af7237a73dec9f242885a7e";
element["similarity"] = 52.59766;
element["img_id"] = "2.jpg";
element["people_name"] = "测试";
array["result"].append(element);
//std::ostringstream ss;
if (writer->write(array, &std::cout))
std::cout << "write failed" << std::endl;
else
std::cout << std::endl;
return ;
}

Compile.bat

g++ -std=c++11 jsoncpp_parse_test.cpp jsoncpp/jsoncpp.cpp -o jsoncpp_parse_test
g++ -std=c++11 jsoncpp_generate_test.cpp jsoncpp/jsoncpp.cpp -o jsoncpp_generate_test