[英]How to find a name in a name/value pair using cJSON
cJSON 提供了一個函數
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string)
我創建了一個測試函數
#include "cJSON.h"
const char *jsonstring = "{\"b\": {\"b1\":\"2b\"}}";
void jsontest(void)
{
cJSON *cJSON_data = cJSON_Parse(jsonstring);
char *buffer = cJSON_Print(cJSON_data);
printf("JSON_String:%s\r\n",buffer);
cJSON *bfound = cJSON_GetObjectItemCaseSensitive(cJSON_data,"b1");
printf("bfound: 0x%08x\n",(char*)bfound);
free(cJSON_data);
free(buffer);
}
輸出是
JSON_String:{
"b": {
"b1": "2b"
}
}
bfound: 0x00000000
`
如果我使用這個字符串,
const char *jsonteststr1 = "{\\"a\\":\\"1\\",\\"b\\":\\"2\\",\\"c\\":\\"3\\"}";
GetObjectItemCaseSensitive()
將找到“a”、“b”和“c”。
GetObjectItemCaseSensitive()
似乎沒有遞歸。
難道我做錯了什么? 我不明白如何使用GetObjectItem()
嗎?
我使用的是 1.7.12 版
cJSON_GetObjectItemCaseSensitive(object, string)
只能得到直接孩子和孩子的兄弟姐妹object
,我們無法通過它發現孩子的子節點。
如果你想獲得2b
的值,那么你應該:
#include "cJSON.h"
const char *jsonstring = "{\"b\": {\"b1\":\"2b\"}}";
void jsontest(void)
{
cJSON *cJSON_data = cJSON_Parse(jsonstring);
char *buffer = cJSON_Print(cJSON_data);
printf("JSON_String:%s\r\n",buffer);
cJSON *bfound = cJSON_GetObjectItemCaseSensitive(cJSON_data,"b"); // cJSON_data only has a child which named "b"
cJSON *b1_found = cJSON_GetObjectItemCaseSensitive(bfound, "b1"); // key/value: <b1, 2b> is in b1_found, not bfound
printf("b1_found: 0x%08x\n",(char*)b1_found);
printf("bfound: 0x%08x\n",(char*)bfound);
cJSON_Delete(cJSON_data); // you should use cJSON_Delete to free the json item.
free(buffer);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.