開始的時候,我以爲是json_tokener_parse導致的Segmentation fault的問題,後來問作者,發現是 json_object_object_foreach的問題。
因爲如果是封裝成一個函數給別人用,別人可能會傳遞一個非json的字符串過來,那程序就會崩了,爲了防止程序崩,要在生成json格式的字符串和遍歷json格式的字符串之間加一個判斷,是否是object或者array等。
我在github上問作者的鏈接:https://github.com/json-c/json-c/issues/623
解決辦法,添加了425-430共6行。
407 void TestSegFunction(void)
408 {
409 int i = 0;
410 char *str = "\"{\"loop_number\":1}\"";
411 int len = strlen(str);
412 struct json_tokener *tok = NULL;
413 // char *str = "{\"loop_number\":1}";
414 json_object *pstObj = NULL;
415 json_object *sonPstObj = NULL;
416 pstObj = json_tokener_parse(str);
417 // pstObj = json_tokener_parse_ex(tok, str, len);
418
419 if (NULL == pstObj)
420 {
421 printf("%s : json_tokener_parse failed.\n", __FUNCTION__);
422 }
423 else
424 {
425 if (json_object_get_type(pstObj) != json_type_object)
426 {
427 json_object_put(pstObj);
428 printf("an error json string!\n");
429 return;
430 }
431 json_object_object_foreach(pstObj, key1, val1)
432 {
433 if (0 == strcmp(key1, LOOP_NUMBER))
434 {
435 i = json_object_get_int(val1);
436 printf("i = %d\n", i);
437 }
438 }
439 }
440 }