jsoncpp
1、什么是JSON
json简单说就是 javascript 中的对象和数组,所以这两种结构就是对象和数组两 种结构,通过这两种结构可以表示各种复杂的结构。
json中的数组用 [] 表示,对象用{}表示
2、json环境搭建
①下载并解压 jsoncpp-master.zip包
②在根目录下,运行 python amalgamate.py
③ 在 根 目 录 中 生 成 dist 文 件 夹 包 含 三 个 文 件 dist/json/json-forwards.h dist/json/json.h dist/json.cpp
④在工程目录下,生成 json文件夹,并拷贝 json.h 到 json目录下。
3、写JSON
该json为一个对象,里边还有一个对象Address和一个数组Phone numbers
key - value结构
{
"FirstName": "John",
"LastName": "Doe",
"Age": 43,
"Address": {
"Street": "Downing Street 10",
"City": "London",
"Country": "Great Britain"
},
"Phone numbers": [
"+44 1234567",
"+44 2345678"
]
}
写json对象和数组 写入到了my.json文件中
#include "json/json.h"
#include <fstream>
#include <iostream>
using namespace Json;
using namespace std;
int main()
{
Value obj;
obj["FirstName"] = "John";
obj["LastName"] = "Doe";
obj["Age"] = 43;
Value objAddr;
objAddr["Street"] = "Downing Street 10";
objAddr["City"] = "London";
objAddr["Country"] = "Great Britain";
obj["Address"] = objAddr;
Value arrPhone;
arrPhone.append("+44 1234567"); // 数组用append
arrPhone.append("+44 2345678");
obj["Phone numbers"] = arrPhone;
string str = obj.toStyledString();
cout << str << endl;
fstream fs("my.json", ios::out);
return 0;
}
4、读JSON
{
"name": "BeJson",
"url": "http://www.bejson.com",
"page": 88,
"isNonProfit": true,
"address": {
"street": "科技园路.",
"city": "江苏苏州",
"country": "中国"
},
"links": [
{
"name":"Google",
"url":"http://www.google.com"
},
{
"name":"Baidu",
"url":"http://www.baidu.com"
},
{
"name":"SoSo",
"url":"http://www.SoSo.com"
}
]
}
读:
#include "json/json.h"
#include <fstream>
#include <iostream>
using namespace std;
using namespace Json;
int main()
{
fstream fs("your.json", ios::in);
if (!fs)
cout << "open error" << endl;
Value val;
Reader reader;
if (reader.parse(fs, val))
{
// cout<<val.toStyledString()<<endl;
cout << val["address"]["city"].asCString() << endl;
cout << val["address"]["street"].asCString() << endl;
cout << val["address"]["country"].asCString() << endl;
Value &v = val["links"];
for (int i = 0; i < v.size(); i++)
{
cout << v[i]["name"] << endl;
cout << (v[i]["url"] = "abcdefg") << endl;
}
}
cout << val.toStyledString() << endl;
return 0;
}
迷失的人迷失了,相逢的人会再相逢