我遇到一個問題,rapidjson庫在報告IsObject()為true時似乎并不一致。
有時當我從Document中檢索到一個Value后,呼叫value.IsObject(),它正確地將其報告為一個Object。但有時它會將我認為應該是一個Object的東西報告為不是一個Object。
下面是一個玩具程式。
。似乎我無意中突變了檔案,因為對vegetables::celery的第二次查找明顯失敗。
#define _CRT_SECURE_NO_DEPRECATE
#include <rapidjson/document.h>/span>
#include <rapidjson/writer.h>/span>
#include <rapidjson/stringbuffer.h>/span>
#include <string.h>
#include <stdio.h>
using namespace rapidjson;
int getInt(Document& jsonDoc, const char* propertyName)
{
if (!jsonDoc.IsObject() ) {
puts("Err: jsonDoc not an object") 。
return 0。
}
char* str = strdup(propertyName)。
char* p = strtok(str, " :");
printf("Looking for property `%s``.
", p)。)
if (!jsonDoc.HasMember(p))
{
printf(" - Error: %s not found, property %s
", p, propertyName)。)
free(str)。
return 0;
}
else; }
{
printf(" - found property '%s' !
", p)。)
}
rapidjson::Value& v = jsonDoc[p];
while (p = strtok(0, " :"/span>)
{
printf("尋找屬性`%s`")
", p)。)
if (v.IsObject()
{
puts(" - v是一個物件,所以我可以看看")。
}
else; }
{
printf(" - ERROR: v is NOT an object, I can't search for %s, property %s not found
", p, propertyName)。)
free(str)。
return 0;
}
if (!v.HasMember(p))
{
printf(" - Error while digging: %s not found, property %s
", p, propertyName)。)
free(str)。
return 0;
}
else; }
printf(" - 發現屬性 '%s'
", p)。)
//otherwise,
v = v[p]; //向樹的更深處推進。
}
int val = v.GetInt()。
printf(" - json got value %s=%d
", propertyName, val)。)
free(str)。
return val。
}
void test1()
{
const char* json = R "STR({
"水果":{
"蘋果":1,
"橙子":553,
"香蕉":900
},
"蔬菜":{
"芹菜":10000。
"卷心菜":10000
}
})STR"。
檔案d;
d.Parse(json)。
int apples = getInt(d, "fruit::apples");
int oranges = getInt(d, "fruit::oranges");
int bananas = getInt(d, "fruit::bananas");
int celery = getInt(d, "vecants::celery");
celery = getInt(d, "vecants::celery")。
int cabbage = getInt(d, "vecants::cabbage") 。
}
int main()
{
test1()。
return 0;
uj5u.com熱心網友回復:
這里有兩個問題。
第一個和主要的:
rapidjson::Value& v = jsonDoc[p];
...
v = v[p];
由于v不是一個變數,而是一個參考,你不會把它設定為一個新的物件,而是改變它參考的原始物件,破壞它。
如果你需要改變下面的物件,請使用rapidjson庫Pointers,或者你可以使用像這里的技巧:
rapidjson::Value* v = &(jsonDoc[p]) 。
...
v = &(*v)[p]。
第二條
在if-else的一些回傳中,你有str的記憶體泄漏,你只在函式的最后釋放它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/331846.html
標籤:
上一篇:在一個手風琴按鈕內排列2個不同的元素-Bootstrap5
下一篇:是否有更好的方法來實作這種布局?
