Json
定义:是数据格式。相较于XML,小、读写快、易解析。
语法规则:
- “名称”:“值”
- 值可以是:数字、字符串(“”)、逻辑值、数组([])、对象({})、null
- 数据有逗号隔开。!最后一个数据不加逗号
RapidJSON
定义: 是一个 C++ 的 JSON 解析器及生成器。
基本类型:
- Value:可以理解为int,或者是bool型变量等其他数据类型。对于定义Value value,只是一个定义,还没有决定其数据类型,如果明确value的值,则其相应的数据类型也就确定了
- Write:将Value数据编码成json合适数据格式
- Reader:是将json格式数据解析成一个Value值
// rapidjson/example/simpledom/simpledom.cpp`
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>
using namespace rapidjson;
int main() {
// 1. 把 JSON 解析至 DOM。
const char* json = "{\"project\":\"rapidjson\",\"stars\":10}";
Document d;
d.Parse(json);
// 2. 利用 DOM 作出修改。
Value& s = d["stars"];
s.SetInt(s.GetInt() + 1);
// 3. 把 DOM 转换(stringify)成 JSON。
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
// Output {"project":"rapidjson","stars":11}
std::cout << buffer.GetString() << std::endl;
return 0;
}
注意一点就是一定要对解析出来的document(JSON解析出来以xml dom形式存在)进行判断