一、Json读取
1. 读文件字符串
std::string data = FileUtils::getInstance()->getStringFromFile("test2.json");
2.解析字符串
Json::Reader reader;
Json::Value root;
reader.parse(data,root,false);
3.访问内容
log("id=%d",root["id"].asInt());
log("name=%s",root["name"].asCString());
log("IQ=%f",root["IQ"].asDouble());
log("msg value money=%d",root["msg"]["money"].asInt());
log("msg value say=%s",root["msg"]["say"].asCString());
示例:
test2.json:
{
“id”:1,
“name”:”mutou”,
“IQ”:99.5,
“msg”:{ “money”:999999,“say”:”hehe” }
}
代码:
void HelloWorld::readChildJson()
{
Json::Reader reader;
Json::Value root;
std::string data = FileUtils::getInstance()->getStringFromFile("test2.json");
if (reader.parse(data,false) == true)
{
log("id=%d",root["id"].asInt());
log("name=%s",root["name"].asCString());
log("IQ=%f",root["IQ"].asDouble());
log("msg value money=%d",root["msg"]["money"].asInt());
log("msg value say=%s",root["msg"]["say"].asCString());
}
}
二、Json写入
1.写内容
Json::Value root;
root["name"] = "Who";
root["IQ"] = 999;
2.生成Json字符串
Json::FastWriter writer;
std::string json_file = writer.write(root);
3.写入文件
FILE* file = fopen("testWirte.json","w");
fprintf(file,json_file.c_str());
fclose(file);
示例:
void HelloWorld::writeJson()
{
Json::Value root;
Json::FastWriter writer;
root["name"] = "Who";
root["IQ"] = 999;
std::string json_file = writer.write(root);
FILE* file = fopen("testWirte.json","w");
fprintf(file,json_file.c_str());
fclose(file);
}