一直用的Jsoncpp这个库,用了很多次,隔几日不用了就又忘记怎么操作了唉,还是老老实实写下来,免得要用又去查资料!
1,读含有数组的json
const char* str = "{\"HELK\": [\"id\",\"name\",\"yantao\",\"gender\",\"Male\"],\"code\": 100,\"msg\": \"\",\"files\": \"\"}";
Json::Reader reader;
Json::Value root;
if (reader.parse(str, root)) // reader将Json字符串解析到root,root将包含Json里所有子元素
{
bool IsArray=root["HELK"].isArray();
for(int i=0;i<root["HELK"].size();++i)
{
std::string value=root["HELK"][i].toStyledString();
printf("%s\n",value.c_str());
}
}
JPG:
2.读obj里面的obj
const char* str = "{\"uploadid\": {\"id\":\"123454\",\"name\":\"yantao\",\"gender\":\"Male\"},\"code\": 100,\"msg\": \"\",\"files\": \"\"}";
Json::Reader reader;
Json::Value root;
reader.parse(str, root); // reader将Json字符串解析到root,root将包含Json里所有子元素
Json::Value obj=root["uploadid"];
string str2 = obj["id"].asString();
printf("%s\n",str2.c_str());
JPG:
3.生成一个json
Json::Value root;
root["id"]=1244235;
root["describe"]="how SB you are";
Json::StyledWriter sw;
std::string res_str = sw.write(root);
std::cout << res_str << std::endl;
4.生成一个json里面有数组
Json::Value root;
root["id"]=1244235;
root["describe"]="how SB you are";
root["Arry"].append("123");
root["Arry"].append("213");
root["Arry"].append("321");
Json::StyledWriter sw;
std::string res_str = sw.write(root);
std::cout << res_str << std::endl;
更多文章:http://blog.csdn.net/what951006
powered by:小乌龟在大乌龟背上~