cJSON:パッケージと解析(一)

2945 ワード

JSON:JavaScript Object Notation、データインタラクティブフォーマット.
cJSON:C言語実装、jsonデータのカプセル化と解析に使用します.
cJSONオープンソースアドレス:https://github.com/DaveGamble/cJSON
テスト文字列:
{
    "name":"sdc",
    "age":24,
    "height":1.78
}

1.パッケージ
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.解析
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
", name->valuestring, age->valueint, height->valuedouble); /* */ cJSON_Delete(root); }

3.テスト
#include
#include
#include
#include"cJSON.h"

int main()
{
    char *json_str = NULL;

    json_str = json_package(JSON_OUT_FORMATE);
    printf("formate:
%s
", json_str); json_parse(json_str); cJSON_free(json_str); json_str = json_package(JSON_OUT_UNFORMATE); printf("unformate:%s
", 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.結果
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)とcJSON_PrintUnformatted(const cJSON*item)この2つの関数はmalloc割り当てメモリを呼び出し、cJSON_を呼び出す必要があります.フリー(void*object)でリリースします.                                                                                                                                                                                                                                        上一篇