JSON&C++操作
特点
- 比txt等纯文本更有结构性
- 比表格等文件更轻便
- JSON 规定字符集是UTF-8
- 对象用{ },数组用[ ]
从字符串中读取
void readStrToJson()
{
string strValue = "xxxxxxxxxxxxxxx";//待读取字符串
Json::Reader reader;
Json::Value value;
if (reader.parse(strValue, value))
{
Json::Value out = value["名称"].asString();
---相关操作---
}
}
Value:是jsoncpp 中最基本、最重要的类,用于表示各种类型的对象,jsoncpp 支持的对象类型可见
Json::ValueType 枚举值;
Value类的对象代表一个JSON值,既可以代表一个文档,也可以代表 文档中一个值。
从文件读取
void readFileToJson()
{
Json::Reader reader;
Json::Value root;
//从文件中读取,保证当前文件有demo.json文件
ifstream in("demo.json", ios::binary);
if (!in.is_open())
{
cout << "Error opening file\n";
return;
}
if (reader.parse(in, root))
{
//此时root可视为根
//通过对象名称继续访问对象
Json::Value out = value["名称"];
//读取子节点信息
Json::Value out_1 = root["名称"]["名称"]
//读取数组信息
for (unsigned int i = 0; i < root["名称"].size(); i++)
{
string str = root["hobby"][i].asString();
}
}
else
{
cout << "parse error\n" << endl;
}
in.close();
}
写JSON文件
思路就是,构建出整个JSON根对象,赋好值,然后通过Writer写入文件就好
Json::FastWriter fw;
ofstream os;
os.open("xxxx.json", std::ios::out | std::ios::app);
if (!os.is_open())
cout << "error:can not find or create the file which named \" xxx.json\"." << endl;
os << fw.write(root);
os.close();
其中,fw为直接写入方式,另外还有缩进写入,root为构建好的根对象
总而言之,
将一个JSON根对象视作一张表,通过reader打开这个表,
value可以是这张表里的一个元组或一个属性或一个元素,统称为一个对象,通过[“名称”]访问不同子对象,通过[序号]遍历数组,
writer则用来写入
1371

被折叠的 条评论
为什么被折叠?



