目录
1、json数据解析
Json::CharReaderBuilder rbuilder;
Json::CharReader* reader = rbuilder.newCharReader();
Json::Value root;
bool parse_ok;
string str;
str=readFileIntoString(); //从json文件读取
parse_ok = reader->parse(str.c_str(),str.c_str() + str.length(), &root, &errs);
if(!parse_ok)
{
printf("parse json error: %s\n",errs.c_str());
return 0;
}else
{
companyid = atoi(root["companyid"].asCString());
printf("companyid:%d\n",companyid);
char *ip = (char*)root["ip"].asCString();
strcpy(SERVER_IP,ip);
}
运行结果:
2、json数据生成
int tcpc_send(int socketfd)
{
Json::Value root;
Json::Value json_array;
Json::StreamWriterBuilder builder;
string str;
int ret;
Json::OStringStream oss;
std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
root["name"] = "robben";
root["msgID"] = "123";
json_array[0] = "weifang";
json_array[1] = "shanghai";
root["city"] = json_array;
writer->write(root,&oss);
str = oss.str();
ret = send(socketfd,str.c_str(),str.length(),0);
return ret;
}
运行结果:
3、json类型判断函数,判断key的类型函数
判断为空:if(root["name"].type() == Json::nullValue)
判断存在:if(root["name"].isNull())或者if(root.isMember(“name”))
判断是string:root["name"].isString
判断是数组:root["name"].isArray()
over...