本文為轉載
原文地址:http://blog.sina.com.cn/s/blog_4c0cb1c00102xg7j.html
使用說明:將cJSON.c、cJSON.h兩個文件,拷貝到工程項目文件中編譯使用即可。
下載地址:https://sourceforge.net/projects/cjson/
主要函數:
【1】常用創建
【創建JSON對象】cJSON *cJSON_CreateObject(void);
【創建JSON數組】cJSON *cJSON_CreateArray(void);
【2】常用添加
【向對象中添加對象】voidcJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
【向數組中添加對象】void cJSON_AddItemToArray(cJSON *array, cJSON *item);
【向對象中添加數值】cJSON_AddNumberToObject(object,name,n)
【向對象中添加字符串】 cJSON_AddStringToObject(object,name,s)
示例:
#include
#include "cJSON.h"
char *makeJson()
{
cJSON *pJsonRoot = NULL;
cJSON *pIntArray = NULL;
cJSON *pCommArray = NULL;
cJSON *pSubJson = NULL;
char *p = NULL;
int intarr[5] = {0, 1, 2, 3, 4}; //整數數組
pJsonRoot = cJSON_CreateObject(); //創建JSON對象
if(NULL == pJsonRoot)
{
//error happend here
return NULL;
}
cJSON_AddStringToObject(pJsonRoot, "hello", "hello world"); //添加一個值為字符串的鍵值對"hello":"hello world"
cJSON_AddNumberToObject(pJsonRoot, "number", 10010); //添加一個值為數值的鍵值對"number": 10010
cJSON_AddBoolToObject(pJsonRoot, "bool", 1); //添加一個值為布爾的鍵值對"bool": 1
pSubJson = cJSON_CreateObject(); //創建另一個json對象作為子對象
if(NULL == pSubJson)
{
// create object faild, exit
cJSON_Delete(pJsonRoot); //刪除pJsonRoot 及其子對象
return NULL;
}
cJSON_AddStringToObject(pSubJson, "subjsonobj", "a sub json string"); //添加一個值為布爾的鍵值對
cJSON_AddItemToObject(pJsonRoot, "subobj", pSubJson); //將對象pSubJson添加到pJsonRoot中,成為鍵值對 "subobj":pSubJson
//數值數組
pIntArray = cJSON_CreateIntArray(intarr, 5); //為intarr創建一個數值數組對象,
cJSON_AddItemToObject(pJsonRoot, "IntArr", pIntArray); //將對象pIntArray添加到pJsonRoot中,成為鍵值對 " IntArr ":pIntArray
//通用數組
pCommArray = cJSON_CreateArray();//創建數組對象
//cJSON_AddItemToArray(cJSON *array, cJSON *item);//向數組中添加對象
cJSON_AddNumberToObject(pCommArray, "num", 2); //向數組中添加數值cJSON_AddNumberToObject(object,name,n)
cJSON_AddStringToObject(pCommArray, "str", "hopeview"); //向對象中添加字符串 cJSON_AddStringToObject(object,name,s)
cJSON_AddItemToObject(pJsonRoot, "pCommArray ", pCommArray); //將對象pCommArray添加到pJsonRoot中,成為鍵值對 " pCommArray ":pCommArray
p = cJSON_Print(pJsonRoot); //json對象轉為json字符串用於傳輸
// else use :
// char * p = cJSON_PrintUnformatted(pJsonRoot);
if(NULL == p)
{
//convert json list to string faild, exit
//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
cJSON_Delete(pJsonRoot); //刪除pJsonRoot 及其子對象
return NULL;
}
//free(p);
cJSON_Delete(pJsonRoot); //釋放json對象
printf("myJson is:%s",p);
return p; //返回json字符串,注意外面用完p要記得釋放空間。//free(p);
}