CJSON解析json字符串示例

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

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

#include <stdio.h>  
#include <stdlib.h>  
#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;  
}
相关推荐
存储服务专家StorageExpert9 分钟前
DELL SC compellent存储的四种访问方式
运维·服务器·存储维护·emc存储
凯子坚持 c11 分钟前
C语言复习概要(三)
c语言·开发语言
zqx_713 分钟前
随记 前端框架React的初步认识
前端·react.js·前端框架
无限大.23 分钟前
c语言200例 067
java·c语言·开发语言
无限大.26 分钟前
c语言实例
c语言·数据结构·算法
Death20029 分钟前
Qt 中的 QListWidget、QTreeWidget 和 QTableWidget:简化的数据展示控件
c语言·开发语言·c++·qt·c#
惜.己30 分钟前
javaScript基础(8个案例+代码+效果图)
开发语言·前端·javascript·vscode·css3·html5
什么鬼昵称1 小时前
Pikachu-csrf-CSRF(get)
前端·csrf
Death2001 小时前
Qt 3D、QtQuick、QtQuick 3D 和 QML 的关系
c语言·c++·qt·3d·c#
洛临_1 小时前
【C语言】基础篇
c语言·算法