精华内容
下载资源
问答
  • 2020-12-20 04:10:55

    这里介绍如何使用cjson,创建一个含数组的json字串。例如下面的形式:

    {

    "UnixSocket":

    [

    {

    "id":0,

    "value":10.0

    }

    ]

    }

    干脆一些,直接上代码:

    int Jsondata_Create_Json(char *pBuf, int id, int type, int value, float fvalue)

    {

    cJSON *root;

    cJSON *Array;

    cJSON *objId;

    char *pStr;

    int ret;

    memset(pBuf, 0, sizeof(pBuf));

    root = cJSON_CreateObject();

    Array = cJSON_CreateArray();

    objId = cJSON_CreateObject();

    cJSON_AddNumberToObject(objId, "id", id);

    if(type == Value_Int)

    {

    cJSON_AddNumberToObject(objId, "value", value);

    }

    else

    {

    cJSON_AddNumberToObject(objId, "value", fvalue);

    }

    cJSON_AddItemToArray(Array, objId);

    cJSON_AddItemToObject(root, "UnixSocket", Array);

    pStr = cJSON_Print(root);

    printf("json is:\r\n%s\r\n", pStr);

    strcpy(pBuf, pStr);

    }

    更多相关内容
  • cJSON结构体构建

    2020-12-20 04:11:26
    cJSON结构体构建一:cJSON构建。1 int create_objects()2 {3 cJSON *root, *fmt, *img, *thm, *fld;4 char *out;5 int i; /* The index number. */6 int ret = 0;78 /* Here we construct several JSO...

    cJSON结构体构建

    一:cJSON的构建。

    1 int create_objects()

    2 {

    3 cJSON *root, *fmt, *img, *thm, *fld;

    4 char *out;

    5 int i; /* The index number. */

    6 int ret = 0;

    7

    8 /* Here we construct several JSON objects. */

    9

    10 // ------------------构建第1个----------------------

    11 /* The "Video" data type: */

    12 root = cJSON_CreateObject();

    13 cJSON_AddItemToObject(root, "name", cJSON_CreateString("Jack (\"Bee\") Nimble"));

    14 cJSON_AddItemToObject(root, "format", fmt = cJSON_CreateObject());

    15 cJSON_AddStringToObject(fmt, "type", "rect");

    16 cJSON_AddNumberToObject(fmt, "width", 1920);

    17 cJSON_AddNumberToObject(fmt, "height", 1080);

    18 cJSON_AddFalseToObject (fmt, "interlace");

    19 cJSON_AddNumberToObject(fmt, "frame rate", 24);

    20

    21 out = cJSON_Print(root); /* Print to text */

    22 cJSON_Delete(root); /* Delete the cJSON object */

    23 LOG_I(cjson_example, "%s\n", out); /* Print out the text */

    24 cJSON_free(out); /* Release the string. */

    25

    26 // ------------------构建第2个----------------------

    27 /* The "days of the week" array: */

    28 const char *strings[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

    29 root = cJSON_CreateStringArray(strings, 7);

    30

    31 out = cJSON_Print(root);

    32 cJSON_Delete(root);

    33 LOG_I(cjson_example, "%s\n", out);

    34 cJSON_free(out);

    35

    36 // ------------------构建第3个----------------------

    37 /* The matrix: */

    38 int numbers[3][3] = {{0, -1, 0}, {1, 0, 0}, {0, 0, 1}};

    39 root = cJSON_CreateArray();

    40 for (i = 0; i < 3; i++) {

    41 cJSON_AddItemToArray(root, cJSON_CreateIntArray(numbers[i], 3));

    42 }

    43

    44 /* cJSON_ReplaceItemInArray(root,1,cJSON_CreateString("Replacement")); */

    45 out = cJSON_Print(root);

    46 cJSON_Delete(root);

    47 LOG_I(cjson_example, "%s\n", out);

    48 cJSON_free(out);

    49

    50 // ------------------构建第4个----------------------

    51 /* The "gallery" item: */

    52 int ids[4] = {116, 943, 234, 38793};

    53 root = cJSON_CreateObject();

    54 cJSON_AddItemToObject(root, "Image", img = cJSON_CreateObject());

    55 cJSON_AddNumberToObject(img, "Width", 800);

    56 cJSON_AddNumberToObject(img, "Height", 600);

    57 cJSON_AddStringToObject(img, "Title", "View from 15th Floor");

    58 cJSON_AddItemToObject(img, "Thumbnail", thm = cJSON_CreateObject());

    59 cJSON_AddStringToObject(thm, "Url", "http:/*www.example.com/image/481989943");

    60 cJSON_AddNumberToObject(thm, "Height", 125);

    61 cJSON_AddStringToObject(thm, "Width", "100");

    62 cJSON_AddItemToObject(img, "IDs", cJSON_CreateIntArray(ids, 4));

    63

    64 out = cJSON_Print(root);

    65 cJSON_Delete(root);

    66 LOG_I(cjson_example, "%s\n", out);

    67 cJSON_free(out);

    68

    69 // ------------------构建第5个----------------------

    70 /* The array of "records": */

    71 struct record fields[2] = {

    72 {"zip", 37.7668, -1.223959e+2, "", "SAN FRANCISCO", "CA", "94107", "US"},

    73 {"zip", 37.371991, -1.22026e+2, "", "SUNNYVALE", "CA", "94085", "US"}

    74 };

    75

    76 root = cJSON_CreateArray();

    77 for (i = 0; i < 2; i++) {

    78 cJSON_AddItemToArray(root, fld = cJSON_CreateObject());

    79 cJSON_AddStringToObject(fld, "precision", fields[i].precision);

    80 cJSON_AddNumberToObject(fld, "Latitude", fields[i].lat);

    81 cJSON_AddNumberToObject(fld, "Longitude", fields[i].lon);

    82 cJSON_AddStringToObject(fld, "Address", fields[i].address);

    83 cJSON_AddStringToObject(fld, "City", fields[i].city);

    84 cJSON_AddStringToObject(fld, "State", fields[i].state);

    85 cJSON_AddStringToObject(fld, "Zip", fields[i].zip);

    86 cJSON_AddStringToObject(fld, "Country", fields[i].country);

    87 }

    88

    89 /* cJSON_ReplaceItemInObject(cJSON_GetArrayItem(root,1),"City",cJSON_CreateIntArray(ids,4)); */

    90 out = cJSON_Print(root);

    91 cJSON_Delete(root);

    92 LOG_I(cjson_example, "%s\n", out);

    93 cJSON_free(out);

    94 return ret;

    95 }

    二:打印如下

    1 {

    2

    3 "name": "Jack (\"Bee\") Nimble",

    4

    5 "format": {

    6

    7 "type": "rect",

    8

    9 "width": 1920,

    10

    11 "height": 1080,

    12

    13 "interlace": false,

    14

    15 "frame rate": 24

    16

    17 }

    18

    19 }

    20

    21 ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

    22

    23 [[0, -1, 0], [1, 0, 0], [0, 0, 1]]

    24

    25 {

    26

    27 "Image": {

    28

    29 "Width": 800,

    30

    31 "Height": 600,

    32

    33 "Title": "View from 15th Floor",

    34

    35 "Thumbnail": {

    36

    37 "Url": "http:/*www.example.com/image/481989943",

    38

    39 "Height": 125,

    40

    41 "Width": "100"

    42

    43 },

    44

    45 "IDs": [116, 943, 234, 38793]

    46

    47 }

    48

    49 }

    50

    51 [{

    52

    53 "precision": "zip",

    54

    55 "Latitude": 37.7668,

    56

    57 "Longitude": -122.3958999999999,

    58

    59 "Address": "",

    60

    61 "City": "SAN FRANCISCO",

    62

    63 "State": "CA",

    64

    65 "Zip": "94107",

    66

    67 "Country": "US"

    68

    69 }, {

    70

    71 "precision": "zip",

    72

    73 "Latitude": 37.371991,

    74

    75 "Longitude": -122.02

    76 。。。

    标签:cJSON,root,out,AddStringToObject,fld,fields,AddNumberToObject

    来源: https://www.cnblogs.com/LiuYanYGZ/p/10259733.html

    展开全文
  • cJSON构建和解析

    2019-11-22 19:57:34
    一、cjson构建 #define MODULE_NUM 3 int encode_Json(){ char nameBuffer[10] = "caotuo"; int id[6] = {1,2,3,4,5,6}; cJSON *root = cJSON_CreateObject(); //在根节点创建cjson对象{} ...

    一、cjson构建

    #define MODULE_NUM 		3
    
    int encode_Json(){
        char nameBuffer[10] = "caotuo";
        int id[6] = {1,2,3,4,5,6};
    
        cJSON *root = cJSON_CreateObject();                    //在根节点创建cjson对象{}  root
        cJSON *name_list_array = cJSON_CreateArray();        //创建数组对象[]  name_list_array    
        cJSON_AddItemToObject(root, "name_list", name_list_array);  //在根节点下添加数组对象[] 并命名为 name_list
        
        for(int i=0; i<MODULE_NUM; i++){
            cJSON *Item = cJSON_CreateObject();               //创建cjson对象{}  Item
            cJSON_AddItemToArray(name_list_array, Item);   //在数组对象[]下添加 cjson对象Item
            cJSON_AddStringToObject(Item, "name", nameBuffer );  //填充数组中的 cjson对象
            cJSON_AddNumberToObject(Item, "id", 0 );
            cJSON_AddNumberToObject(Item, "num_error", 0 );
            cJSON_AddNumberToObject(Item, "num_warning", 0 );
        }
    
        cJSON_AddItemToObject(root, "list_nums", cJSON_CreateNumber(1));
        cJSON_AddItemToObject(root, "list_date", cJSON_CreateString("20191122"));
    	
        cJSON *id_list_array = cJSON_CreateArray();		//创建数组对象[]  id_list_array
        cJSON_AddItemToObject(root, "id_arraay", id_list_array); //在根节点下添加数组对象[]
        for(int i=0; i<6; i++){
    	    cJSON_AddNumberToObject(id_list_array, "id_arraay", id[i]);  //填充数组对象[]
        }
    
        char *buffer = cJSON_Print(root);
        printf("\n\n%s\n\n", buffer);
    }

    打印结果:

    {
        "name_list":    [{
                "name":    "caotuo",
                "id":    0,
                "num_error":    0,
                "num_warning":    0
            }, {
                "name":    "caotuo",
                "id":    0,
                "num_error":    0,
                "num_warning":    0
            }, {
                "name":    "caotuo",
                "id":    0,
                "num_error":    0,
                "num_warning":    0
            }],
        "list_nums":    1,
        "list_date":    "20191122",
        "id_arraay":    [1, 2, 3, 4, 5, 6]
    }

    二、cjson解析

    假设有一个json格式的文本文件,现在需要解析里面的每一个键对应的value值。步骤如下:

    1.open文件,该文件内容如下(待解析的json文本)

    {"rootError": [
    		{"name": "volt_error", 
    		 "struct": [{"code": "111", "brief": "aaaaa", "type": "Warning", "light": "Y", "mod": "module1", "id": "7"}, {"code": "222", "brief": "bbbbb", "type": "Warning", "light": "Y", "mod": "module2", "id": "7"}, {"code": "333", "brief": "ccccc", "type": "Error", "light": "Y", "mod": "module3", "id": "2"}]
                    }, 
    		{"name": "current_error", 
    		 "struct": [{"code": "444", "brief": "ddddd", "type": "Error", "light": "N", "mod": "module4", "id": "2"}]
                    }
    	      ]
    }

    2.read到缓存中*buffer

    3.用 cJSON * root = cJSON_Parse(buffer);  将缓存中的数据解析为cjson对象格式,并获得根节点root。此时可以通过char *buffer2 = cJSON_PrintUnformatted(root); 来打印buffer2,也就是cjson对象格式

    int decode_cJson()
    {
        int fd;
        int ret = -1;
        int size = 0;
        char buffer[65532];
    
        fd = open(FILE_ERROR_CODE, O_RDONLY);
        read(fd, buffer, sizeof(buffer));
        close(fd);
    
        cJSON * root = cJSON_Parse(buffer);
        cJSON * head = cJSON_GetObjectItem(root, "rootError");
        size = cJSON_GetArraySize(head);//rootError数组成员的数量 size=2
    	
        for(int i=0; i<size; i++)
        {
            cJSON * tab = cJSON_GetArrayItem(head, i);
            cJSON * data = cJSON_GetObjectItem(tab, "struct");
            int tabsize = cJSON_GetArraySize(data);//struct数组成员的数量 tabsize=3、1
    		
            for(int j=0; j<tabsize; j++)
            {
                cJSON * item = NULL;
                cJSON * index = cJSON_GetArrayItem(data, j);        
                item = cJSON_GetObjectItem(index, "code");
                
                if(item != NULL && item->valuestring != NULL)
                {
                    printf("code=%s\n", item->valuestring);
                    int code = atoi(item->valuestring);
    				
                    item = cJSON_GetObjectItem(index, "brief");
                    if(item != NULL && item->valuestring != NULL)
                        sprintf(info->brief, "%s", item->valuestring);
                    printf("brief=%s\n", item->valuestring);
    				
                    item = cJSON_GetObjectItem(index, "type");
                    if(item != NULL && item->valuestring != NULL)
                        sprintf(info->type, "%s", item->valuestring);
                    printf("type=%s\n", item->valuestring);
    				
                    item = cJSON_GetObjectItem(index, "light");
                    if(item != NULL && item->valuestring != NULL){
                    if(0 == strcmp(item->valuestring, "Y"))
                        int light = 1;
                    else
                        int light = 0;
                    }
                    printf("light=%s\n", item->valuestring);
    				
                    item = cJSON_GetObjectItem(index, "id");
                    if(item != NULL && item->valuestring != NULL){
                        int id = atoi(item->valuestring);		
                    }
                    printf("id=%s\n", item->valuestring);
    				
                	//cJSON_Delete(root);
                    //return 0;
                    ret = 0;
                }
                
            }
        }
    
        char *buffer2 = cJSON_PrintUnformatted(root);
        *len = strlen(buffer2);
        printf("buffer2=%s\n\n", buffer2);
    
        free(buffer2);
        cJSON_Delete(root);
    	
        return ret;
    }

     

    展开全文
  • CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); 2. 字符串 cJSON库函数: //在对象中添加字符串 CJSON_PUBLIC(cJSON*) cJSON_...

    C语言:JSON格式详解
    C语言:cJSON库用法详解
    C语言:使用cJSON库构造JSON
    C语言:使用cJSON库解析JSON字符串


    一、构造简单的JSON字符串

    1. 数字

    cJSON库函数:

    //在对象中添加数字
    CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
    

    2. 字符串

    cJSON库函数:

    //在对象中添加字符串
    CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
    

    3. 逻辑值

    cJSON库函数:

    //在对象中添加逻辑值
    CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);//在对象中添加null
    CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);//在对象中添加true
    CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);//在对象中添加false
    

    具体代码如下:

    #include <stdio.h>
    #include "cJSON.h"
    
    int main(void)
    {
    	char *name = "MQ";
    	int	age = 25;
    	double height = 183.52;
    	
    	cJSON *TCP = cJSON_CreateObject();				//创建一个对象
    	
    	cJSON_AddStringToObject(TCP,"name",name);		//添加字符串 
    	cJSON_AddNumberToObject(TCP,"age",age);	    	//添加整型数字 
    	cJSON_AddNumberToObject(TCP,"height",height);	//添加浮点型数字
    	cJSON_AddFalseToObject(TCP,"gender");			//添加逻辑值false 
    	
     	cJSON_AddStringToObject(TCP,"name","MQ");		//添加字符串 
    	cJSON_AddNumberToObject(TCP,"age",25);	    	//添加整型数字 
    	cJSON_AddNumberToObject(TCP,"height",183.52);	//添加浮点型数字
    	cJSON_AddFalseToObject(TCP,"gender");			//添加逻辑值false
    	
    	char *json_data = cJSON_Print(TCP);				//JSON数据结构转换为JSON字符串
    	printf("%s\n",json_data);						//输出字符串
    	cJSON_Delete(TCP);								//清除结构体
    	return 0;
    }
    

    运行结果如下:

    {
            "name": "MQ",
            "age":  25,
            "height":       183.52,
            "gender":       false,
            
            "name": "MQ",
            "age":  25,
            "height":       183.52,
            "gender":       false
    }
    

    注意:定义浮点型(float)数据时,要使用双浮点型(double)定义。否则小数点后就会输出长串数字,导致失败。

    定义结果
    float183.52000427246094
    double183.52

    二、构造嵌套数组的JSON字符串

    1. 数字型数组

    cJSON库函数:

    //创建整型数组
    CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
    //创建浮点型数组---这个使用会出问题,需要浮点型可以使用双浮点型函数。
    CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
    //创建双浮点型数组
    CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
    

    具体代码如下:

    #include <stdio.h>
    #include "cJSON.h"
    
    int main(void)
    {
    	int		time[4]={123,456,789,150};
    	float	grade1[4]={66.51,118.52,61.53,128.54};
    	double  grade2[4]={66.51,118.52,61.53,128.54};
    	
    	cJSON *TCP = cJSON_CreateObject();	//创建一个对象
    	
    	cJSON *TIM  = cJSON_CreateIntArray(time,4);		//创建一个整型数组
    	cJSON_AddItemToObject(TCP,"time",TIM);
    	cJSON *GRA1  = cJSON_CreateFloatArray(grade1,4);	//创建一个浮点型数组
    	cJSON_AddItemToObject(TCP,"grade",GRA1);
    	cJSON *GRA2  = cJSON_CreateDoubleArray(grade2,4);	//创建一个双浮点型数组
    	cJSON_AddItemToObject(TCP,"grade",GRA2);
    	
    	char *json_data = cJSON_Print(TCP);		//JSON数据结构转换为JSON字符串
    	printf("%s\n",json_data);	//输出字符串
    	cJSON_Delete(TCP);	//清除结构体
    	return 0;
    }
    

    运行结果如下:

    {
            "time": [123, 456, 789, 150],
            "grade": [66.510002136230469, 118.51999664306641, 61.529998779296875, 128.53999328613281],
            "grade": [66.51, 118.52, 61.53, 128.54]
    }
    

    注意:通过运行结果可以看出,使用浮点型(float)函数会出现小数点后输出长串数字的现象,导致失败。具体原因不明,有没有技术大佬知道原因,可以在评论区留言,谢谢!

    2. 字符型数组

    cJSON库函数:

    //创建字符型数组---这个使用会出问题,下面有替代方法。
    CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count);
    

    这函数使用总是出错,具体原因不明,有没有技术大佬知道原因,可以在评论区留言,谢谢!
    具体替代方法代码如下:

    #include <stdio.h>
    #include "cJSON.h"
    
    int main(void)
    {
    	char subject[5][6]={"政治","数学","英语","专业课"};
    	
    	cJSON *TCP = cJSON_CreateObject();				//创建一个对象
    	
    	cJSON *SUB1  = cJSON_CreateArray();				//创建一个数组	
    	cJSON_AddStringToObject(SUB1,"","政治"); 		//添加字符串到数组
     	cJSON_AddStringToObject(SUB1,"","数学");		//添加字符串到数组
    	cJSON_AddStringToObject(SUB1,"","英语");		//添加字符串到数组
    	cJSON_AddStringToObject(SUB1,"","专业课");		//添加字符串到数组
    	cJSON_AddItemToObject(TCP,"subject",SUB1);		//添加数组到对象
    	
    	cJSON *SUB2  = cJSON_CreateArray();				//创建一个数组
    	cJSON_AddStringToObject(SUB2,"",subject[0]); 	//添加字符串到数组
     	cJSON_AddStringToObject(SUB2,"",subject[1]);	//添加字符串到数组
    	cJSON_AddStringToObject(SUB2,"",subject[2]);	//添加字符串到数组
    	cJSON_AddStringToObject(SUB2,"",subject[3]);	//添加字符串到数组
    	cJSON_AddItemToObject(TCP,"subject",SUB2);		//添加字符串到数组
    	
    	char *json_data = cJSON_Print(TCP);				//JSON数据结构转换为JSON字符串
    	printf("%s\n",json_data);//输出字符串
    	cJSON_Delete(TCP);//清除结构体
    	return 0;
    }
    

    运行结果如下:

    {
            "subject": ["政治", "数学", "英语", "专业课"],
            "subject": ["政治", "数学", "英语", "专业课"]
    }
    

    3. 对象型数组

    cJSON库函数:

    CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);	//创建对象
    CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);	//创建数组
    CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item);	//在数组中添加项目
    

    具体代码如下:

    #include <stdio.h>
    #include "cJSON.h"
    
    int main(void)
    {
    	cJSON *TCP = cJSON_CreateObject();			//创建一个对象
    	cJSON *STU  = cJSON_CreateArray();			//创建一个数组
    	
    	cJSON *Z3  = cJSON_CreateObject();			//创建一个对象
    	cJSON_AddStringToObject(Z3,"name","张三");	//添加字符串 
    	cJSON_AddNumberToObject(Z3,"age",24);	    //添加整型数字 
    	cJSON_AddTrueToObject(Z3,"gender");			//添加逻辑值 
    	cJSON_AddItemToArray(STU,Z3);				//添加对象到数组中 
    	
    	cJSON *L4  = cJSON_CreateObject();			//创建一个对象
    	cJSON_AddStringToObject(L4,"name","李四");	//添加字符串 
    	cJSON_AddNumberToObject(L4,"age",25);	    //添加整型数字 
    	cJSON_AddTrueToObject(L4,"gender");			//添加逻辑值 
    	cJSON_AddItemToArray(STU,L4);				//添加对象到数组中
    	
    	cJSON *W5  = cJSON_CreateObject();			//创建一个对象
    	cJSON_AddStringToObject(W5,"name","王五");	//添加字符串 
    	cJSON_AddNumberToObject(W5,"age",26);	    //添加整型数字 
    	cJSON_AddTrueToObject(W5,"gender");			//添加逻辑值 
    	cJSON_AddItemToArray(STU,W5);				//添加对象到数组中
    	
    	cJSON_AddItemToObject(TCP,"student",STU);   //添加数组到对象中
    
    	
    	char *json_data = cJSON_Print(TCP);	//JSON数据结构转换为JSON字符串
    	printf("%s\n",json_data);//输出字符串
    	cJSON_Delete(TCP);//清除结构体
    	return 0;
    }
    

    运行结果如下:

    {
       "student":[
    				{"name":"张三","age":24,"gender":ture},
    				{"name":"李四","age":25,"gender":ture},
    				{"name":"王五","age":26,"gender":ture},
     	 		  ]	
    }
    

    三、构造嵌套对象的JSON字符串

    cJSON库函数:

    CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);	//创建对象
    CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);//在对象中添加数字
    CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);//在对象中添加字符串
    CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);	//在对象中添加项目
    

    具体代码如下:

    #include <stdio.h>
    #include "cJSON.h"
    
    int main(void)
    {
    	cJSON *TCP = cJSON_CreateObject();				//创建一个对象
    	
    	cJSON *ADD	= cJSON_CreateObject();				//创建一个对象
    	cJSON_AddStringToObject(ADD,"country","China");	//添加字符串 
    	cJSON_AddNumberToObject(ADD,"zip-code",123456);	//添加整型数字
     	cJSON_AddItemToObject(TCP,"address",ADD);
     	
    	cJSON *Z3  = cJSON_CreateObject();			//创建一个对象
    	cJSON_AddStringToObject(Z3,"name","张三");	//添加字符串 
    	cJSON_AddNumberToObject(Z3,"age",24);	    //添加整型数字 
    	cJSON_AddTrueToObject(Z3,"gender");			//添加逻辑值 
    	cJSON_AddItemToObject(TCP,"student1",Z3);				
    	 
    	cJSON *L4  = cJSON_CreateObject();			//创建一个对象
    	cJSON_AddStringToObject(L4,"name","李四");	//添加字符串 
    	cJSON_AddNumberToObject(L4,"age",25);	    //添加整型数字 
    	cJSON_AddTrueToObject(L4,"gender");			//添加逻辑值 
    	cJSON_AddItemToObject(TCP,"student2",L4);
    	
    	cJSON *W5  = cJSON_CreateObject();			//创建一个对象
    	cJSON_AddStringToObject(W5,"name","王五");	//添加字符串 
    	cJSON_AddNumberToObject(W5,"age",26);	    //添加整型数字 
    	cJSON_AddTrueToObject(W5,"gender");			//添加逻辑值 
    	cJSON_AddItemToObject(TCP,"student3",W5);
    	
    	char *json_data = cJSON_Print(TCP);		//JSON数据结构转换为JSON字符串
    	printf("%s\n",json_data);//输出字符串
    	cJSON_Delete(TCP);//清除结构体
    	return 0;
    }
    

    运行结果:

    {
    	"address":{
    				"country":      "China",
    				"zip-code":     123456
    			  },
    	"student1":{
    				"name": "张三",
    				"age":  24,
    				"gender":       true
    			   },
    	"student2":{
    				"name": "李四",
    				"age":  25,
    				"gender":       true
    			   },
    	"student3":{
    				"name": "王五",
    				"age":  26,
    				"gender":       true
    		       }
    }
    

    四、构造无格式的JSON字符串

    cJSON库函数:

    CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);//JSON数据结构转换为JSON字符串---有格式
    CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);	//JSON数据结构转换为JSON字符串---无格式
    

    具体示例代码如下:

    #include <stdio.h>
    #include "cJSON.h"
    
    int main(void)
    {
    	double  grade[4]={66.51,118.52,61.53,128.54};
    	int		time[4]={123,456,789,150};
    	
    	cJSON *TCP = cJSON_CreateObject();				//创建一个对象
    	
     	cJSON_AddStringToObject(TCP,"name","MQ");		//添加字符串 
    	cJSON_AddNumberToObject(TCP,"age",25);	    	//添加整型数字 
    	cJSON_AddNumberToObject(TCP,"height",183.52);	//添加浮点型数字
    	cJSON_AddFalseToObject(TCP,"gender");			//添加逻辑值false
    	 
    
    	cJSON *ADD	= cJSON_CreateObject();				//创建一个对象
    	cJSON_AddStringToObject(ADD,"country","China");	//添加字符串 
    	cJSON_AddNumberToObject(ADD,"zip-code",123456);	//添加整型数字
     	cJSON_AddItemToObject(TCP,"address",ADD);
     	
    	cJSON *SUB  = cJSON_CreateArray();				//创建一个数组
    	cJSON_AddStringToObject(SUB,"","政治"); 		//添加字符串到数组
     	cJSON_AddStringToObject(SUB,"","数学");
    	cJSON_AddStringToObject(SUB,"","英语");
    	cJSON_AddStringToObject(SUB,"","专业课");
    	cJSON_AddItemToObject(TCP,"subject",SUB);		//添加数组到对象
    	
    	cJSON *TIM  = cJSON_CreateIntArray(time,4);		//创建一个整型数组
    	cJSON_AddItemToObject(TCP,"time",TIM);
    	
    	cJSON *GRA  = cJSON_CreateDoubleArray(grade,4);	//创建一个双浮点型数组
    	cJSON_AddItemToObject(TCP,"grade",GRA);
    	
    	cJSON *STU  = cJSON_CreateArray();			//创建一个数组
    	
    	cJSON *Z3  = cJSON_CreateObject();			//创建一个对象
    	cJSON_AddStringToObject(Z3,"name","张三");	//添加字符串 
    	cJSON_AddNumberToObject(Z3,"age",24);	    //添加整型数字 
    	cJSON_AddTrueToObject(Z3,"gender");			//添加逻辑值 
    	cJSON_AddItemToArray(STU,Z3);				//添加对象到数组中 
    	
    	cJSON *L4  = cJSON_CreateObject();			//创建一个对象
    	cJSON_AddStringToObject(L4,"name","李四");	//添加字符串 
    	cJSON_AddNumberToObject(L4,"age",25);	    //添加整型数字 
    	cJSON_AddTrueToObject(L4,"gender");			//添加逻辑值 
    	cJSON_AddItemToArray(STU,L4);				//添加对象到数组中
    	
    	cJSON *W5  = cJSON_CreateObject();			//创建一个对象
    	cJSON_AddStringToObject(W5,"name","王五");	//添加字符串 
    	cJSON_AddNumberToObject(W5,"age",26);	    //添加整型数字 
    	cJSON_AddTrueToObject(W5,"gender");			//添加逻辑值 
    	cJSON_AddItemToArray(STU,W5);				//添加对象到数组中
    	
    	cJSON_AddItemToObject(TCP,"student",STU);	//添加数组到对象中
    
    	char *json_data = cJSON_PrintUnformatted(TCP);	//JSON数据结构转换为JSON字符串
    	printf("%s\n",json_data);//输出字符串
    	cJSON_Delete(TCP);//清除结构体
    	return 0;
    }
    

    运行结果:

    {"name":"MQ","age":25,"height":183.52,"gender":false,"address":{"country":"China","zip-code":123456},"subject":["政治","数学","英语","专业课"],"time":[123,456,789,150],"grade":[66.51,118.52,61.53,128.54],"student":[{"name":"张三","age":24,"gender":true},{"name":"李四","age":25,"gender":true},{"name":"王五","age":26,"gender":true}]}
    

    cJSON源码库下载地址

    展开全文
  • cJSON对于cJSON的使用,我主要是用来模拟远程服务器端返回的一个json类型的目录结构,客户端进行获取并进行解析,把解析出来的目录按照原本的结构显示在本地。cJSON简介cJSON是一个超轻巧,携带方便,单文件,简单的...
  • 一、前言:为了使用简单方便,可以通过下载cJSON文件来解析JOSN字符串比较简单方便,而且cJSON文件只有一个cJSON.c和cJSON.h两个文件,使用起来效率比较高。三、使用说明:将下载到的文件解压出来,里面只有cJSON.c...
  • 使用cJSON库构造JSON

    2021-12-14 09:38:39
    CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); 2. 字符串 cJSON库函数: //在对象中添加字符串 CJSON_PUBLIC(cJSON*) cJSON_...
  • 下面举例如何创建json字符串: static void post_data_to_clouds(void) { cJSON *pMain = cJSON_CreateObject(); //首先创建一个对象,后面的数据都会填充到这里面 cJSON *pArray = cJSON_CreateArray(); //数组 ...
  • cJson数组的生成与解析

    千次阅读 2021-01-05 15:27:28
    cJson数组的生成与解析 cJosn官方源码地址:https://sourceforge.net/projects/cjson/ 使用json偶尔会遇到数组,每次都要去查相关函数,去解析或者生成,在此做一次记录,方便以后使用。按照我自己的使用习惯,根据...
  • cJSON对象的构建

    2020-12-20 04:10:57
    # cJSON对象的构建## 开始阅读源代码**上面的文章中我们我们抓住了一条线,通过一个测试函数的实现来了解整个项目中的部分功能,当然,这不会覆盖所有的源代码,但我们会有一个清晰的思路来一步一步由点及面逐渐看清...
  • cJSON源码,用于C语言json数据的构建与解析
  • 使用cJSON构建json串特别简单,只需引入两个文件(cJSON.h与cJSON.c)即可。将这两个文件包含到工程中,然后引用头文件cJson.h,接下来使用相关函数构建Json串即可。
  • cjson 数据构建

    2021-04-20 15:02:38
    需要使用cjson发送数据 方案: 与json类似,cjson分为两种,一种是对象类型的,一种是数组类型的,分别使用 extern cJSON *cJSON_CreateArray(void); extern cJSON *cJSON_CreateObject(void); 接着便是挂载节点到...
  • cJSON解析库的使用示例,包含简单和复杂JSON字符串的解析和构建
  • 使用cJSON库解析和构建JSON字符串前言其实之前的两篇博文已经介绍了json格式和如何使用cJSON库来解析JSON:当时在MCU平台上使用时,会出现时间长了死机的情况,在调用cJSON_Print输出格式化后的JSON数据之后,LOG(...
  • 控制器STM32F407+MDK5.34+cJSON1.7.7 二、安装cJSON MDK中打开Pack Install,选择Generic下边MDK-Pack::cJSON,点击安装Install 安装成功后,在Manage Run-Time Environment 中找到Data Exchange,并选择cJSON...
  • 本文用代码简单介绍cjson的使用方法,1)创建json,从json中获取数据。2)创建json数组和解析json数组1、创建json,从json中获取数据1 #include 2 #include "cJSON.h"34 char *makeJson()5 {6 cJSON * pJsonRoot =NULL...
  • ESP32学习笔记(12)——JSON接口使用

    千次阅读 2021-05-07 09:26:35
    释放链表占用的内存空间 void cJSON_Delete(cJSON *c) 获取cJSON对象数组成员的个数 int cJSON_GetArraySize(cJSON *array) 根据下标获取cJSON对象数组中的对象 cJSON *cJSON_GetArrayItem(cJSON*array,int item) ...
  • 1、先要有cJOSN库,两个文件分别是cJSON.c和cJSON.h。2、感性认识char * json = "{ \"json\" : { \"id\":1, \"nodeId\":11, \"deviceId\":111, \"deviceName\":\"aaa\", \"ieee\":\"01212\", \"ep\":\"1111\", \...
  • C语言中 cjson 的解析和构建

    千次阅读 2018-06-22 13:41:54
    json构建cJSON * jsonHead = NULL; cJSON * jsonListArray = NULL; cJSON * jsonItem = NULL; jsonHead = cJSON_CreateObject(); cJSON_AddItemToObject(jsonHead, JSON_CHAT_UI_MEMBER_...
  • 在使用cJSON_AddItemToArray方法添加item时出现了问题,在此记录一下。 测试使用的json对象: { "services": [ { "name": "TXT", "servers": [ { "name"...
  • 基于VS的cJSON应用工程

    2021-10-13 22:39:08
    基于VS的cJSON应用工程,主要是使用cJSON构建自己的数据结构体,然后使用cJSON来进行解析到自己的数据

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,469
精华内容 587
关键字:

cjson构建