CJSON

1.JSON简介 XML protobuff

JSON(JavaScript Object Notation)是-种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition 二December 1999的一个子集。JSON 采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C+ +, C#, Java, JavaScript, Per, Python等)。 这些特性便JSON成为理想的数据交换语言。跟XML相比, JSON的优势在于格式简洁短小,特别是在处理大量复杂数据的时候,这个优势便显得非常突出。从各浏览器的支持来看,JSON 解决了因不同浏览器对XML DOM解析方式不同而引起的问题。

2.JSON建构于两种结构:

“名称/值"对的集合(A collection of name/value pairs) 。 不同的语言中,它被理解为对象(object),纪录(record), 结构(struct)。字典(dictionary),哈希表(hash table)。有键列表(keyed list) ,或者关联数组(associative array)。// key, value;

值的有序列表(An ordered list ofvalues) 。在大部分语言中,它被理解为数组(array) .

这些都是常见的数据结构。事实上大部分现代计算机语言都以某种形式支持它们。这使得一种数据格式在同样基于这些结构的编程语言之间交换成为可能。

3.形式

对象是一个无序 的" ’ 名称/值’ 对"集合。一个对象以"("(左括号)开始,")"(右括号)结束。每个”名称“后跟一个”:“" ’ 名称/值’ 对"之间使用“,”(逗号)分隔。

图16

数组是值(value) 的有序集合。一个数组以"[”(左中括号) 开始,“I” (右中括号) 结束。值之间使用”," (逗号)分隔。

图17

值(value)可以是双引号括起来的字符串(string) 、数值(number)、 true、false、 null、对象(object) 或者数组(array) 。这些结构可以嵌套。

图18

字符串(string) 是由双引号包围的任意数量Unicode字符的集合,使用反斜线转义。一个字符(character) 即一个单独的字符串(character string)。字符串(string) 与C或者Java的字符串非常相似。

图19

数值(number)也与c或者Java的数值非常相似。除去未曾使用的八进制与十六进制格式。除去一些编码细节。

图20

{
   
    "c_type":["char","short","int","long","double","bool"]
}
{
   
    "name":"akashi",
    "age":18,
    "love":["basketball","reading"],
    "score":145,
    "address":"Tokyo"
}

4.CJSON数据类型

CJSON对象的类型:

json_type_object. "名称/值"对的集合

json对象值的类型

json_type_boolean

json_type_double

json_type_int

json_type_arrary “值”的集合

json_type_string

/*cJSON Types:*/
#define cJSON False  0
#define cJSON True   1
#define cJSON NULL   2
#define cJSON Number 3
#define cJSON String 4

5.CJSON的API

1)向JSON提供malloc和free函数

extern void CJSON InitHooks(c JSON Hooks* hooks):

2)提供一个JSON块,然后返回-个可以查询的CJSON对象。完成后调用CJSON Delete.

extern JSON *CJSON Parse(const char *value);

3)将JSON实体呈现为用于传输/存储的文本。完成后释放char*.

extern char *CJSON Print(JSON *item);

4)将CJSON实体呈现为用于传输/存储的文本,而不进行任何格式化。完成后释放char*.

extern char *CJSON PrintUnformatted(CJSON *item); .

5)使用缓冲策略将JSON实体呈现为文本。预缓冲是对最终大小的猜测。猜测减少了重新分配。fmt=0 表示无格式,

extern char *CJSON PrintBuffered(JSON *item,int prebufferint fmt);

6)删除一个CJSON实体和所有子实体。

extern void CJSON Delete(CJSON *C);

7)返回数组(或对象)中的项数。

extern int CJSON GetArraySize(CJSON *array);

8)从数组“数组"中检索项目编号“项目" .如果不成功,返回NULL。

extern CJSON *CJSON GetArrayltem(CJSON *array,int item);

9)从对象中获取项目"string".不区分大小写。

extern JSON *CJSON GetObjectltem(CJSON *object,const char *string);

10)用于分析失败的语法。这将返回-个指向解析错误的指针。

你可能需要回头看几个字才能理解它。当CJSON Parse0返回0时定义。当CSON Parse0成功时为0。*/

extern const char *CISON GetrrorPtr(void);

11)这些调用创建适当Type的CJSON项。
extern JSON *CJSON CreateNullvoid);
extern JSON *CJSON CreateTrue(void);
extern CJSON *CJSON CreateFalse(void);
extern CSON *CJSON CreateBool(int b);
extern JSON *CJSON CreateNumber(double num);
extern JSON *JSON CreateString(const char *string);
extern cJSON *CJSON CreateArray(void);
extern CJSON *CJSON CreateObject(void);

根据count创建数组。
extern CJSON *CJSON CreateFloatArray(const float *numbers,int count);
extern CJSON *CJSON CreateFloatArray(const float *numbers,int count);
extern JSON *CJSON CreateDoubleArray(const double *numbersint count);
extern CJSON *CJSON CreateStringArray(const char **strings,int count);

12)向指定的数组/对象追加项。
extern void JSON AddltemToArray(CJSON *array, CJSON *item);
externvoid IJSON AddltemToObject(JSON tobject,const char *string.JSON *item);
extern void CJSON AddltemToObjectCS(CJSON *objectconst char *sting,CJSON *item);
当字符串确实是常量(例如,是一个文本, 或者与常量一样好)。 并且肯定会在JSON对象中存活时,就使用这个方法.

13)将对项的引用追加到指定的数组/对象。当您想要将现有的CJSON添加到新的JSON中,但又不想破坏现有的c JSON时,可以使用此方法。
extern void JSON AddltemReference ToAray(CJSON tarray, CJSON *item);
extern void CJSON AddtemReference ToObject(JSON tobject,const char *string,CJSON titem);
14)从数组/对象中删除/分离项。
extern CJSON *CJSON DetachltemFromArray(CJSoN *array,int which);
extern void JSON DeleteltemFromArray(CJSON arrayint which);
extern CJSON *CJSON DetachltemFromObject(CJSON *object.const char *string);
externvoid JSON DeleteltemFromObjet(CJSON *object.const char *string);
15)更新数组项
extern void JSON InsertitemlnArray(CJSON arryint which.JSON *newitem);
p将已存在的项目向右移动。
extern void JSON ReplaceltemlnArray(JSON tarray,int which,cJSON *newitem);
extern void CISON ReplaceltemInobject(CJSON *object,const char *String.CJSON newitem);
16)复制一个JSON项目
extern CJSON CJSON Duplicate(cJSON * item.int recurse);
/
Duplicate将在需要释放的新内存中创建一个与传递的JSON相同的新项目。 递归!=0,它将复制连接到该项的所有子元素。目-> next和- >prev指针在从Duplicate返回时总是0。
/

17)ParseWithOpts允许您要求(井检查)SON是否以null结尾,并检索指向解析后的最终字节的指针。
extern JSON *CJSON ParseWithOpts(const char *value,const char **return parse end, int require null _terminated);
extern void JSON Minify(char *json);
18)用于快速创建内容的宏。
#define JSON_AddNullToObject(object,name) JSON_AddltemToObject(object, name, JSON_CreateNull())
#define JSON_AddTrueToObject(objectname) JSON_AddltemTobject(object, name, JSON_CreateTrue() )
#define JSON__AddFalseToObject(object,name) JSON_AddltemToObject(object, name, CJSON_CreateFalse())
#define CJSON_AddBoolTobject(objectname,b) JSON_AdditemToObject(object, name, JSON_CreateBool(b) )
#define JSON AddNumberToObject(object.name,n)

JSON_AddltemToObject(object, name,JSON_CreateNumber(n) )
#define JSON_AddStringToobject( object,name,s)

JSON_AddltemToObject(object, name,CJSON_CreateString(s))
19)在分配整数值时,也需要将其传播到valuedouble.
#define CJSON_SetIntValue(object,val)

((object)?(object)->valueint=(object)->valuedouble=(val):(val))
#define cJSON_SetNumberValue(object,val)

((object)?(object)->valueint=(object)->valuedouble=(val):(val))

int main(void)
{
   
    char。data= "{\"c_type\:[\"char\",\"short\"int\"]}";
	//从缓冲区中解析出JSON结构
	cJSON * json= cJSON_Parse(data);
	//将传入的ISON结构转化为字符串并打印
	char "json_data = NULL: 
	printf(" data:%s\n",json_data = cJSON_Print[json]); 
	free[json_data]:
	//将JSON结构所占用的数据空间释放
	cJSON_Delete[json]:
	return 0;
}

cJSON.h

#ifndef cJSON__h
#define cJSON__h

#ifdef __cplusplus
extern "C"
{
   
#endif

/* cJSON Types: */
#define cJSON_False 0
#define cJSON_True 1
#define cJSON_NULL 2
#define cJSON_Number 3
#define cJSON_String 4
#define cJSON_Array 5
#define cJSON_Object 6
	
#define cJSON_IsReference 256

/* The cJSON structure: */
typedef struct cJSON 
{
   
	struct cJSON *next,*prev;	
	struct cJSON *child;		
	int type;					
	char *valuestring;			
	int valueint;				
	double valuedouble;			
} cJSON;

typedef struct cJSON_Hooks 
{
   
      void *(*malloc_fn)(size_t sz);
      void (*free_fn)(void *ptr);
} cJSON_Hooks;

/* Supply malloc, realloc and free functions to cJSON */
extern void cJSON_InitHooks(cJSON_Hooks* hooks);


/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
extern cJSON *cJSON_Parse(const char *value);
/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
extern char  *cJSON_Print(cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
extern char  *cJSON_PrintUnformatted(cJSON *item);
/* Delete a cJSON entity and all subentities. */
extern void   cJSON_Delete(cJSON *c);

/* Returns the number of items in an array (or object). */
extern int	  cJSON_GetArraySize(cJSON *array);
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);
/* Get item "string" from object. Case insensitive. */
extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);

/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
extern const char *cJSON_GetErrorPtr(void);
	
/* These calls create a cJSON item of the appropriate type. */
extern cJSON *cJSON_CreateNull(void);
extern cJSON *cJSON_CreateTrue(void);
extern cJSON *cJSON_CreateFalse(void);
extern cJSON *cJSON_CreateBool(int b);
extern cJSON *cJSON_CreateNumber(double num);
extern cJSON *cJSON_CreateString(const char *string);
extern cJSON *cJSON_CreateArray(void);
extern cJSON *cJSON_CreateObject(void);

/* These utilities create an Array of count items. */
extern cJSON *cJSON_CreateIntArray(int *numbers,int count);
extern cJSON *cJSON_CreateFloatArray(float *numbers,int count);
extern cJSON *cJSON_CreateDoubleArray(double *numbers,int count);
extern cJSON *cJSON_CreateStringArray(const char **strings,int count);

/* Append item to the specified array/object. */
extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);
extern void	cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
extern void	cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item);

/* Remove/Detatch items from Arrays/Objects. */
extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which);
extern void   cJSON_DeleteItemFromArray(cJSON *array,int which);
extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string);
extern void   cJSON_DeleteItemFromObject(cJSON *object,const char *string);
	
/* Update array items. */
extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem);
extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);

/* Duplicate a cJSON item */
extern cJSON *cJSON_Duplicate(cJSON *item,int recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
need to be released. With recurse!=0, it will duplicate any children connected to the item.
The item->next and ->prev pointers are always zero on return from Duplicate. */

/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
extern cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated);

/* Macros for creating things quickly. */
#define cJSON_AddNullToObject(object,name)		cJSON_AddItemToObject(object, name, cJSON_CreateNull())
#define cJSON_AddTrueToObject(object,name)		cJSON_AddItemToObject(object, name, cJSON_CreateTrue())
#define cJSON_AddFalseToObject(object,name)		cJSON_AddItemToObject(object, name, cJSON_CreateFalse())
#define cJSON_AddBoolToObject(object,name,b)	cJSON_AddItemToObject(object, name, cJSON_CreateBool(b))
#define cJSON_AddNumberToObject(object,name,n)	cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n))
#define cJSON_AddStringToObject(object,name,s)	cJSON_AddItemToObject(object, name, cJSON_CreateString(s))

/* When assigning an integer value, it needs to be propagated to valuedouble too. */
#define cJSON_SetIntValue(object,val)			((object)?(object)->valueint=(object)->valuedouble=(val):(val))

#ifdef __cplusplus
}
#endif

#endif

cJSON.c

#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <limits.h>
#include <ctype.h>
#include "cJSON.h"

static const char *ep;

const char *cJSON_GetErrorPtr(void) 
{
   
    return ep;
}

static int cJSON_strcasecmp(const char *s1,const char *s2)
{
   
	if (!s1) return (s1==s2)?0:1;
    if (!s2) return 1;
	for(; tolower(*s1) == tolower(*s2); ++s1, ++s2)		if(*s1 == 0)	return 0;
	return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2);
}

static void *(*cJSON_malloc)(size_t<
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值