2015-02-11 93 views
0

我試圖通過解析然而在JSON的第一個數字不斷得到變爲0第一個數字是始終爲0

我使用cJSON一個網絡服務器一個CGI文件接收的JSON文件「VE由代碼一小段我使用來測試此其中:

int main(int argc, char *argv[]) 
{ 
    cJSON *pstReq; 
    char *pcReq = getenv("QUERY_STRING"); 

    printf("Content-Type: application/json\n\n"); 

    URLDecode(pcReq) /* Decodes the query string to JSON string */ 
    pstReq = cJSON_Parse(pstReq); 

    printf("%d\n", cJSON_GetObjectItem(pstReq, "test")->valueint); 
    printf("%d\n", cJSON_GetObjectItem(pstReq, "test2")->valueint); 
    printf(cJSON_Print(pstReq)); 

    return EXIT_SUCCESS; 
} 

跑過JSON {‘測試’:123,‘TEST2’:123}到此通過查詢字符串導致程序輸出:

0 
123 
{"test":0, "test2":123} 

我完全不知道我在這裏做錯了什麼,如果有人能給我一些關於這個問題的想法,我會非常感激。

回答

0

如果不知道URLDecode是如何工作的,或者從環境中檢索到pcReq的原始內容,它很難知道。我會從沒有網絡的情況下運行這個代碼開始,將cJSON作爲一個小單元來測試,這可能會揭示出現問題的原因。

首先,幫助我們理解你的代碼,在代碼如下:

pstReq = cJSON_Parse(pstReq); 

我認爲你的意思是:

pstReq = cJSON_Parse(pcReq); 

考慮到這一點,我會先運行此代碼:

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

int main(int argc, char *argv[]) 
{ 
    cJSON *pstReq; 

    char *pcReq = "{\"test\":123, \"test2\":123}"; 
    pstReq = cJSON_Parse(pcReq); 

    printf("%d\n", cJSON_GetObjectItem(pstReq, "test")->valueint); 
    printf("%d\n", cJSON_GetObjectItem(pstReq, "test2")->valueint); 
    printf("%s\n",cJSON_Print(pstReq)); 

    return EXIT_SUCCESS; 
} 

這個按我期望的那樣工作。

如果這樣也爲您生成正確的輸出結果,我會在URLDecode()之前和之後添加printf()來查看pcReq中包含的內容。這個問題可能來自'pcReq'本身。因此,在短期,這將是可能給你的問題出在哪裏的想法代碼:我希望這有助於發現問題

int main(int argc, char *argv[]) 
{ 
    cJSON *pstReq; 
    char *pcReq = getenv("QUERY_STRING"); 

    printf("Content-Type: application/json\n\n"); 

    printf ("=== pcReq before decoding ===\n"); 
    printf("%s\n",pcReq); 
    printf ("=============================\n"); 

    URLDecode(pcReq); /* Decodes the query string to JSON string */ 

    printf ("=== pcReq after decoding ===\n"); 
    printf("%s\n",pcReq); 
    printf ("=============================\n"); 

    pstReq = cJSON_Parse(pcReq); 

    printf("%d\n", cJSON_GetObjectItem(pstReq, "test")->valueint); 
    printf("%d\n", cJSON_GetObjectItem(pstReq, "test2")->valueint); 
    printf("%s\n",cJSON_Print(pstReq)); 

    return EXIT_SUCCESS; 
} 

+0

感謝您的回覆,我試着運行您發佈在我的Linux機器上的第一段代碼,並確保足夠的一切按預期運行。然而,當我添加了printf(「Content-Type:application/json \ n \ n」);'並嘗試在系統上運行它時,我原來一直在運行該程序(Cubox)我以前有過輸出。這讓我相信代碼實際上是正確的,問題是由與Cubox相關的其他因素以及它的設置引起的。 – KGB 2015-02-12 18:44:58