首先我们要确定要保存json文件的格式,只有事先确定json文件的格式,才能构造它。
{
"age" : 24,
"array" : [
{
"cancel" : "取消",
"loginfail" : "登录失败",
"loginsuccess" : "登录成功",
"ok" : "确定"
},
{
"cancel" : "取消",
"loginfail" : "登录失败",
"loginsuccess" : "登录成功",
"ok" : "确定"
},
{
"cancel" : "取消",
"loginfail" : "登录失败",
"loginsuccess" : "登录成功",
"ok" : "确定"
}
],
"name" : "HaKing"
}
void writeJson()
{
std::string filePath = "/Users/Fsy/Desktop/C++/Json/king.json";
std::ofstream fout;
fout.open(filePath.c_str());
assert(fout.is_open());
Json::Value root; // 根节点
root["name"] = "HaKing"; // 根节点下"name"对应的值"HaKing"
root["age"] = 24; // 根节点下"age"对应的值24
Json::Value array; // 创建数组
for (int i = 0; i < 3; i++)
{
Json::Value item;
item["ok"] = "确定";
item["cancel"] = "取消";
item["loginsuccess"] = "登录成功";
item["loginfail"] = "登录失败";
array.append(item); // append()以数组的形式添加
}
root["array"]= array;
std::string out = root.toStyledString();
std::cout << out << std::endl;
fout << out << std::endl;
}