码迷,mamicode.com
首页 > Web开发 > 详细

CJSON实例详解

时间:2014-10-18 16:54:20      阅读:294      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   sp   数据   

先贴代码

 1 #include <stdio.h>
 2 #include "cJSON.h"
 3 
 4 int main()
 5 {
 6     cJSON * pJsonRoot = NULL;
 7 
 8     pJsonRoot = cJSON_CreateObject();
 9     if(NULL == pJsonRoot)
10     {
11         //error happend here
12         return 0;
13     }
14     cJSON_AddStringToObject(pJsonRoot, "hello", "hello world");
15     cJSON_AddNumberToObject(pJsonRoot, "number", 10010);
16     cJSON_AddBoolToObject(pJsonRoot, "bool", 1);
17     cJSON * pSubJson = NULL;
18     pSubJson = cJSON_CreateObject();
19     if(NULL == pSubJson)
20     {
21         // create object faild, exit
22         cJSON_Delete(pJsonRoot);
23         return 0;
24     }
25     cJSON_AddStringToObject(pSubJson, "subjsonobj", "a sub json string");
26     cJSON_AddItemToObject(pJsonRoot, "subobj", pSubJson);
27 
28     char * p = cJSON_Print(pJsonRoot);
29     if(NULL == p)
30     {
31         //convert json list to string faild, exit
32         //because sub json pSubJson han been add to pJsonRoot, so just delete pJsonRoot, if you also delete pSubJson, it will coredump, and error is : double free
33         cJSON_Delete(pJsonRoot);
34         return 0;
35     }
36     printf("%s\n", p);
37 
38     return 0;
39 }

centos下编译通过,运行如下:

1 {
2     "hello":    "hello world",
3     "number":    10010,
4     "bool":    true,
5     "subobj":    {
6         "subjsonobj":    "a sub json string"
7     }
8 }

代码解释如下:

CJSON在内存中的存储方式是用链表进行存储的,所以在进行操作的时候,我们可见的部分全部是用指针进行操作的。

第8行新建一个JSON项目。

第14、15、16行分别添加了字符串、数字和bool变量。

第18行新建一个JSON项目:pSubJson。

第25行在新建的pSubJson项目上添加字符串。

第26行把我们的新项目添加到最初的项目pJsonRoot上。

第28行把CJSON的内存的存储的数据转换为字符串格式。

cjson库的下载地址在:http://pan.baidu.com/s/1ntsRLgt

 

CJSON实例详解

标签:style   blog   http   color   io   os   ar   sp   数据   

原文地址:http://www.cnblogs.com/fengbohello/p/4033272.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!