2015-02-11 88 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