【问题标题】:First number in JSON parsed with CJSON is always 0用 CJSON 解析的 JSON 中的第一个数字始终为 0
【发布时间】:2019-01-29 09:49:10
【问题描述】:

我正在尝试使用 cJSON 解析由网络服务器上的 CGI 文件接收的 JSON 文件,但是 JSON 中的第一个数字不断更改为 0。

我编写了一小段代码来测试它:

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 {"test":123, "test2":123} 传递给 this 会导致程序输出以下内容:

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

我完全不知道我在这里做错了什么,如果有人能给我一些关于问题可能是什么的想法,我将不胜感激。

【问题讨论】:

    标签: c json cgi cjson


    【解决方案1】:

    如果不知道 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;
    }
    

    这对我来说按预期工作。

    如果这也为您生成正确的输出,我将添加 printf() 以查看 URLDecode() 之前和之后 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;
    }
    

    我希望这有助于找到问题。

    【讨论】:

    • 感谢您的回复,我尝试运行您在我的 linux 机器上发布的第一段代码,果然一切都按预期运行。但是,当我添加行 printf("Content-Type: application/json\n\n"); 并尝试在我最初在(Cubox)上运行程序的系统上运行它时,我得到了与以前相同的错误输出。这使我相信代码实际上是正确的,并且问题是由与 Cubox 及其设置方式相关的其他一些因素引起的。
    猜你喜欢
    • 2014-06-15
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多