1)基本数据类型的读取
{
"name": "fengyuzaitu",
"age": 29.5,
"married": false,
"utcsecond": 1548745708,
"utcmilisecond":1548745708000
}
std::ifstream ifs;
ifs.open("testdata.json", std::ios::binary);
Json::Reader reader(Json::Features::strictMode());
Json::Value root;
if (NULL == reader.parse(ifs, root))
{
ifs.close();
return;
}
ifs.close();
if (!root["name"].isString()) return;
if (!root["age"].isDouble()) return;
if (!root["married"].isBool()) return;
if (!root["utcsecond"].isInt()) return;
if (!root["utcmilisecond"].isInt64()) return;
std::string strName = root["name"].asString();
double dAge = root["age"].asDouble();
bool bMarried = root["married"].asBool();
int32_t nUtcSecond = root["utcsecond"].asInt();
int64_t nUtcMiliSecond = root["utcmilisecond"].asInt64();
2)字符串数组
{
"success":false,
"toReturn":[
{
"createTime":"20080806114526000+0800",
"createUser":"张三"
},
{
"createTime":"20080806114526000+0801",
"createUser":"李四"
}
],
"total":2
}
std::string strTotalNumber = root["total"].asString();
Json::Value subValue = root["toReturn"];
if (subValue.isNull()) return;
size_t count = subValue.size();
for (size_t i = 0; i < count; i++)
{
std::string strCreateTime = subValue[i]["createTime"].asString();
std::string strCreateUser = subValue[i]["createUser"].asString();
}
3)数据内嵌json文本
一般情况下如下是一个正常的json文本
{
"msg":{
"absTime":1521699455000,
"ext":{"vehicleColor":"A","monitorId":"85ee85b052dd228a08494e11858060f4"}
},
"systemMessage":"1"
}
但是如下,将ext的内容通过双引号包含,变成了一个字符串,解析就需要特别注意
文本内容:
{
"msg":{
"absTime":1521699455000,
"ext":"{"vehicleColor":"A","monitorId":"85ee85b052dd228a08494e11858060f4"}"
},
"systemMessage":"1"
}
内存查看
{
"msg":
{
"absTime": 1521699455000,
"ext": "{\"vehicleColor\":\"A\",\"monitorId\":\"85ee85b052dd228a08494e11858060f4\"}"
},
"systemMessage": "1"
}
通过转义来区分双引号,第一步获取到ext对应的字符串,然后重新解析该字符串
Json::Value msg;
Json::Reader readerMsg(Json::Features::strictMode());
if(NULL == readerMsg.parse(strMsg, msg) return;
std::string strExt = msg["ext"].asString();
Json::Value ext;
Json::Reader readerExt(Json::Features::strictMode());
if (readerer.parse(strExt, ext))
{
std::string strColor = ext["vehicleColor"].asString();
std::string strMonitorId = ext["monitorId"].asString();
}