cJSON: packaging and resolved (a)

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

JSON: JavaScript Object Notation, A data interchange format.

cJSON: C language, for packaging and parsing json data.

cJSON Open Source Address: https://github.com/DaveGamble/cJSON

1. Packaging

enum json_print_formate
{
    JSON_OUT_FORMATE = 0,    /*按 json 格式输出*/
    JSON_OUT_UNFORMATE,      /*以字符串形式输出*/
};

char *json_package(enum json_print_formate flag)
{
    cJSON *root = NULL;   
    char *out = NULL;

    root =cJSON_CreateObject();   /*根*/
    cJSON_AddStringToObject(root, "name", "sdc");  /*添加字符串*/
    cJSON_AddNumberToObject(root, "age", 24);      /*添加整型*/
    cJSON_AddNumberToObject(root, "height", 1.78);  /*添加浮点型*/

    if(JSON_OUT_FORMATE == flag)
    {
        out = cJSON_Print(root);   
    }
    else
    {
        out = cJSON_PrintUnformatted(root);/*将json形式打印成正常字符串形式*/
    }

    /*释放内存*/  
    cJSON_Delete(root);     

    return out;
}

2. Parse

void json_parse(char *json_string)
{
    cJSON *root = NULL;
    cJSON *name = NULL;
    cJSON *age = NULL;
    cJSON *height = NULL;
    
    root = cJSON_Parse(json_string); /*解析成json形式*/
    name = cJSON_GetObjectItem(root, "name");  /*获取键值内容*/
    age = cJSON_GetObjectItem(root, "age");
    height = cJSON_GetObjectItem(root, "height");

    printf("name:%s,age:%d,height:%f\n", name->valuestring, age->valueint, height->valuedouble);
 
    /*释放内存*/
    cJSON_Delete(root);  
}

3. Test

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"cJSON.h"

int main()
{
    char *json_str = NULL;

    json_str = json_package(JSON_OUT_FORMATE);
    printf("formate:\n%s\n", json_str);
    json_parse(json_str);
    cJSON_free(json_str);

    json_str = json_package(JSON_OUT_UNFORMATE);
    printf("unformate:%s\n", json_str);
    json_parse(json_str);
    cJSON_free(json_str);
}

   CMakeLists.txt

cmake_minimum_required(VERSION 3.5)

project(json_test)

include_directories(./)

aux_source_directory(./ SRC_FILES)

add_executable(${PROJECT_NAME} ${SRC_FILES})

4. Results

formate:
{
	"name":	"sdc",
	"age":	24,
	"height":	1.78
}
name:sdc,age:24,height:1.780000
unformate:{"name":"sdc","age":24,"height":1.78}
name:sdc,age:24,height:1.780000

Note:

cJSON_Print (const cJSON * item) and cJSON_PrintUnformatted (const cJSON * item) these two function calls malloc to allocate memory, you need to call cJSON_free (void * object) to be released.                                                                                                                                                                         

Guess you like

Origin blog.csdn.net/shizhe0123/article/details/94742514