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;
}
作者: mengchao
出处:https://www.cnblogs.com/meng-chao/p/16064705.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)