我正在尝试使用 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} 传递到此中会导致程序输出以下内容:
0
123
{"test":0, "test2":123}
我完全不知道我在这里做错了什么,如果有人能给我一些关于问题可能是什么的想法,我将不胜感激。
最佳答案
如果不知道 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;
}
我希望这有助于找到问题。
关于c - 使用 CJSON 解析的 JSON 中的第一个数字始终为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28464475/