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;  
}
相关推荐
li理几秒前
核心概念:Navigation路由生命周期是什么
前端
古夕3 分钟前
my-first-ai-web_问题记录02:Next.js 15 动态路由参数处理
前端·javascript·react.js
梦里寻码3 分钟前
自行食用 uniapp 多端 手写签名组件
前端·uni-app
前端小白19955 分钟前
面试取经:工程化篇-webpack性能优化之热替换
前端·面试·前端工程化
正在努力的小河37 分钟前
Linux设备树简介
linux·运维·服务器
小张快跑。39 分钟前
Tomcat下载、安装及配置详细教程
java·服务器·tomcat
随笔记1 小时前
使用vite新搭建react项目,都需要配置什么?
前端·react.js·vite
JiangJiang1 小时前
🩸 一次失败的降级迁移尝试 **从 Vite + React 19 到 CRA + React 17 的 IE 兼容血泪史**
前端
moyu841 小时前
静态声明与动态拦截:从Object.defineProperty到Proxy
前端
kuxku1 小时前
下一代前端工具链浅析
前端·架构