CJSON解析json字符串示例

cJSON 作为 Json 格式的解析库,其主要功能就是构建和解析 Json 格式

CJSON解析json字符串 {"action":"started","code":"0","data":"","desc":"success","sid":"a8"}

#include   
#include   
#include "cJSON.h"  
  
int main() {  
    char *json_string = "{\"action\":\"started\",\"code\":\"0\",\"data\":\"\",\"desc\":\"success\",\"sid\":\"a8\"}";  
      
    // 解析JSON字符串  
    cJSON *root = cJSON_Parse(json_string);  
    if (root == NULL) {  
        printf("Error before: [%s]\n", cJSON_GetErrorPtr());  
        return 1;  
    }  
      
    // 获取各个字段的值  
    cJSON *action = cJSON_GetObjectItem(root, "action");  
    cJSON *code = cJSON_GetObjectItem(root, "code");  
    cJSON *data = cJSON_GetObjectItem(root, "data");  
    cJSON *desc = cJSON_GetObjectItem(root, "desc");  
    cJSON *sid = cJSON_GetObjectItem(root, "sid");  
      
    // 输出各个字段的值  
    printf("action: %s\n", action->valuestring);  
    printf("code: %s\n", code->valuestring);  
    printf("data: %s\n", data->valuestring);  
    printf("desc: %s\n", desc->valuestring);  
    printf("sid: %s\n", sid->valuestring);  
      
    // 释放内存  
    cJSON_Delete(root);  
      
    return 0;  
}

你可能感兴趣的:(常用软件开发工具推荐,前端,服务器,C语言,CJSON,嵌入式)