2017-07-21 37 views
0

这是我的JSON对象:阅读每个对象的所有键 - 值对在阵列

{ 
    "resources":[ 
     { 
      "Foo":0, 
      "Bar":"", 
      "Fiz":1 
     }, 
     { 
      "Foo":2, 
      "Bar":"", 
      "Fiz":3 
     } 
    ] 
} 

上面JSON阵列resources被正确地检测为array。我想迭代数组中的每个对象,并将key:value对添加到map

它确实检测到物体的数量(这里是:2)。 但如何迭代对象成员?有一个断言,数组中的每个元素都不是一个对象。我不懂为什么!

这里是我的代码:

if (jsonvalue->IsArray()){ // that jsonvalue is my "resources" array 
    for (rapidjson::SizeType i = 0; i < jsonvalue->Size(); i++){ 
     const rapidjson::Value& c = jsonvalue[i]; 
     // Is no object! assertion triggers in next call. 
     for (rapidjson::Value::ConstMemberIterator iter = c.MemberBegin(); iter != c.MemberEnd(); ++iter){ 
      printf("%s\t", iter->name.GetString()); 
      printf("%s\t", iter->value.GetString()); 
     } 
    } 
} 

回答

0

你对待所有值string但在你的JSON存在具有Int类型的值项。因此,在打印之前,您需要首先检查每个value的类型。

下面是一个例子:

printf("%s\t", iter->name.GetString()); 

if (iter->value.IsInt()) 
{ 
    printf("%d\t", iter->value.GetInt()); 
} 
else if (iter->value.IsString()) 
{ 
    printf("%s\t", iter->value.GetString()); 
} 

我不知道你为什么不使用C++为基础的范围for循环迭代11。 RapidJSON对此提供支持。见Example

您的代码将更具可读性和紧凑性。