<
4. 了解JsonCPP
https://sourceforge.net/projects/jsoncpp/
https://github.com/open-source-parsers/jsoncpp
用JsonCPP解析一个JSON字符串
用JsonCPP写入一个JSOn字符串
1. {
2. employee :
3. {
4. firstName: "John",
5. lastName : "Doe",
6. employeeNumber : 123,
7. title : "Accountant"
8. }
9. }
1. <employee>
2. <firstName>John</firstName>
3. <lastName>Doe</lastName>
4. <employeeNumber>123</employeeNumber>
5. <title>Accountant</title>
6. </employee>
>
/*******************************************************************
json的相关学习: http://blog.youkuaiyun.com/kxc0720/article/details/48422595#
一个对象以“{”(左括号)开始,“}”(右括号)结束。
每个“名称”后跟一个“:”(冒号);名称/值 之间使用“,”(逗号)分隔
employee :
{
firstName:"John",
lastName:"Doe",
employeeNumber:123,
title:"Accountant"
}
*******************************************************************/
#pragma comment(lib, "json_vc71_libmtd.lib")
#include <fstream>
#include <cassert>
#include "json.h"
#include<stdio.h>
#include<iostream>
using namespace std;
void readJson() {
using namespace std;
const char* str = "{\"firstName\": \"John\",\"lastName\": \"Doe\",\"employeeNumber\": 123,\"title\": \"Accountant\"}";
Json::Reader reader;
Json::Value root;
if (reader.parse(str, root)) // reader将Json字符串解析到root,root将包含Json里所有子元素
{
std::string fname = root["firstName"].asString(); // firstName:"John",
cout << "firstName: "<<fname << endl;
std::string lname = root["lastName"].asString(); // lastName:"Doe",
cout <<"lastName: "<< lname << endl;
int num = root["employeeNumber"].asInt(); //employeeNumber:123,
cout <<"employeeNumber: "<< num << endl;
std::string tile = root["title"].asString(); // title:"Accountant"
cout << "title:"<<tile << endl;
}
}
void writeJson(){
using namespace std;
Json::Value root;
root["firstName"] = "John";
root["lastName"] = "Doe";
root["employeeNumber"] = 123;
root["title"] = "Accountant";
std::cout <<"================================"<<endl<< root.toStyledString().c_str() << std::endl;
}
int main(int argc, char** argv) {
readJson();
writeJson();
getchar();
return 0;
}