1. 程式人生 > >利用jsoncpp庫生成和解析json字串

利用jsoncpp庫生成和解析json字串

jsoncpp庫的使用:

1.生成json字串方法1:藉助value和writer

string uid_str = "10000911";
string account = "vip1";
string json_str;
Json::Value value;
Json::FastWriter writer;
value["uid"] = uid_str;
value["account"] = account;

json_str = writer.write(value);

2.生成json字串方法2:直接賦值

string json_msg = "{\"ret\":0,\"msg\":\"success\"}";//需要轉義雙引號,冒號無需轉義

3.解析json字串

string jsonStr = "{\"uid\":101,\"msg\":\"charge_in_game\"}";
Json::value value;
if(!Json::FromString(value,jsonStr))
{
//error log
//return false;
}
if(!value.isObject())
{
//error log
//return false;
}
unsigned uid = 0;
string msg;
if(!Json::GetUInt(value,"uid",uid))
{
//error log
//return false;
}
if(!Json::GetString(value,"msg",msg))
{
//error log
//return false;
}