如果已知json的key便很容易能够从json得字符串中解出value值,
但是在未知key的情况下,便只能遍历json字符串,找到所需要的值
使用rapidjson遍历字符串代码如下:
#include<iostream>
#include"rapidjson/document.h"
#include"rapidjson/writer.h"
#include"rapidjson/stringbuffer.h"
#include<string>
using namespace rapidjson;
using namespace std;
int main()
{
string strJsonTest = "{\"item_1\":\"value_1\",\"item_2\":\"value_2\",\"item_3\":\"value_3\",\"item_4\":\"value_4\",\"item_arr\":[\"arr_vaule_1\",\"arr_vaule_2\"]}";
Document docTest;
docTest.Parse<0>(strJsonTest.c_str());
if (!docTest.HasParseError())
{
for (rapidjson::Value::ConstMemberIterator itr = docTest.MemberBegin(); itr != docTest.MemberEnd(); itr++)
{
Value jKey;
Value jValue;
Document::AllocatorType allocator;
jKey.CopyFrom(itr->name, allocator);
jValue.CopyFrom(itr->value, allocator);
if (jKey.IsString())
{
string name = jKey.GetString();
printf("\r\nname: %s\r\n", name.c_str());
}
if (jValue.IsString())
{
std::cout << "jValue" << jValue.GetString() << std::endl;
}
}
}
return 0;
}