2015-08-18 33 views
2

我使用由Dave Gamble提供的cJSON並存在以下問題。 如果我更改cJSON結構中的值,然後使用cJSON_Print命令,我不會獲取更新的值,而是仍然獲得默認值。cJSON_Print dosen't顯示更新的值

#include <stdio.h> 
#include <stdlib.h> 
#include "cJSON.h" 

void main(){ 
    cJSON *test = cJSON_Parse("{\"type\":  \"rect\", \n\"width\":  1920, \n\"height\":  1080, \n\"interlace\": false,\"frame rate\": 24\n}"); 
    printf("cJSONPrint: %s\n cJSONvalueint: %d\n",cJSON_Print(test), cJSON_GetObjectItem(test,"frame rate")->valueint); 
    cJSON_GetObjectItem(test,"frame rate")->valueint=15; 
    printf("cJSONPrint: %s\n cJSONvalueint: %d\n",cJSON_Print(test), cJSON_GetObjectItem(test,"frame rate")->valueint); 
} 

這是我用一個小的測試代碼,這讓我的結果:

cJSONPrint: { 
    "type": "rect", 
    "width": 1920, 
    "height": 1080, 
    "interlace": false, 
    "frame rate": 24 
} 

cJSONvalueint: 24 
cJSONPrint: { 
    "type": "rect", 
    "width": 1920, 
    "height": 1080, 
    "interlace": false, 
    "frame rate": 24 
} 
cJSONvalueint: 15 

有誰知道我做錯了什麼,以及如何用正確的值cJSON_Print命令?

回答

1

我認爲你需要使用cJSON_SetIntValue宏。

它將valueint和valueouble設置爲對象而不是valueint。

#include <stdio.h> 
#include <stdlib.h> 
#include "cJSON.h" 

void main(){ 
    cJSON *test = cJSON_Parse("{\"type\":  \"rect\", \n\"width\":  1920, \n\"height\":  1080, \n\"interlace\": false,\"frame rate\": 24\n}");  
    printf("cJSONPrint: %s\n cJSONvalueint: %d\n",cJSON_Print(test), cJSON_GetObjectItem(test,"frame rate")->valueint); 

    cJSON_SetIntValue(cJSON_GetObjectItem(test, "frame rate"), 15); 

    printf("cJSONPrint: %s\n cJSONvalueint: %d\n",cJSON_Print(test), cJSON_GetObjectItem(test,"frame rate")->valueint); 
} 

,將返回:

$ ./test 
cJSONPrint: { 
     "type": "rect", 
     "width":  1920, 
     "height":  1080, 
     "interlace": false, 
     "frame rate": 24 
} 
    cJSONvalueint: 24 
cJSONPrint: { 
     "type": "rect", 
     "width":  1920, 
     "height":  1080, 
     "interlace": false, 
     "frame rate": 15 
} 
    cJSONvalueint: 15 
+0

這爲我工作。非常感謝你。 – PaulB

+0

不客氣。你能接受答案嗎? :) – sig11

+0

對不起,我是新來的Stackoverflow,並沒有得到你的意思。希望一切都好,再次感謝。 – PaulB