c - 如何使用 cJSON 读取字符串

标签 c json cjson

我正在使用 cJSON但不知何故我无法让字符串工作:

void myfile()
{
  cJSON* type = NULL;
  char text1[]="{\n\"name\": \"Jack (\\\"Bee\\\") Nimble\", \n\"format\": {\"type\":       \"rect\", \n\"width\":      1920, \n\"height\":     1080, \n\"interlace\":  false,\"frame rate\": 24\n}\n}";
  cJSON * root = cJSON_Parse(text);
  cJSON * format = cJSON_GetObjectItem(root,"format"); 
  int framerate = cJSON_GetObjectItem(format,"frame rate")->valueint;
  type = cJSON_GetObjectItem(format,"type")->valuestring;
  char * rendered = cJSON_Print(root);
  cJSON_Delete(root);
  printf("rate = %d, type = %s \n", framerate, type) ;
}

我只得到垃圾。我也试过这个,但它甚至没有编译:

char *type[] = cJSON_GetObjectItem(format,"type")->valuestring;

最佳答案

char text[]="{\n\"name\": \"Jack (\\\"Bee\\\") Nimble\", \n\"format\": {\"type\":       \"rect\", \n\"width\":      1920, \n\"height\":     1080, \n\"interlace\":  false,\"frame rate\": 24\n}\n}";
cJSON * root   = cJSON_Parse(text);
cJSON * format = cJSON_GetObjectItem(root,"format"); 
cJSON * type   = cJSON_GetObjectItem(format,"type");
int framerate = cJSON_GetObjectItem(format,"frame rate")->valueint;
char * rendered = cJSON_Print(root);
printf("%s\n", rendered);
printf("rate = %d, type = %s \n", framerate, type->valuestring);
free(rendered);
cJSON_Delete(root);

关于c - 如何使用 cJSON 读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34097942/

相关文章:

c - 如何在 cJSON 和 protobuf 字节变量之间进行转换

c - 如何在 C Linux 中解析 JSON 响应?

cJson如何计算打印缓冲区的长度

c - 包括另一个内部 .c 文件中的函数?

c - 应该更慢,但更快。为什么?

c++ - 从数据库中搜索时间复杂度为 O(1)\O(log n) 的行

javascript - 如何从嵌套 JSON 响应 Angular.js 列出项目(渲染)

c - 如何正确使用 memcpy 而不会出现段错误?

ios - 我如何解析这个 JSON Pokemon 字典? Sprite 宝可梦 API (swift 3)

json - ConvertFrom-Json : Invalid object passed in, ':' 或 '}' 预期