刚刚收获了一个赞,所以才写这最后一篇。appweb对json这种应用最广的网络协议自然有支持,无论是解析还是拼装,我就大概写一下。
解析
/**
Get a request param
@description Get the value of a named request param. Form variables are define via www-urlencoded query or post
data contained in the request.
@param conn HttpConn connection object
@param var Name of the request param to retrieve
@param defaultValue Default value to return if the variable is not defined. Can be null.
@return String containing a reference to the the request param's value. Caller should not mutate this value.
Returns defaultValue if not defined.
@ingroup HttpRx
@stability Stable
*/
PUBLIC cchar *httpGetParam(HttpConn *conn, cchar *var, cchar *defaultValue);
这个函数就是对json的完美解析。使用方法太简单了,不需要说什么。conn是http的结构体指针,var是要查询的字符串,defaultValue是没找到的默认值。
拼装
拼装用到3个函数,创建json结构体指针,往json中插入成员,把json变成字符串。就这简单的3个步骤,操作使用起来非常的简答。需要注意的就是有几个宏来指定是用[]还是{},要不要带“”,元素是什么参数类型。按照下面这3个步骤去操作就能拼装出json字符串。
1.创建json结构体指针
MprJson* json = mprCreateJson(MPR_JSON_OBJ);//MPR_JSON_ARRAY用[],MPR_JSON_OBJ用{}
2.向json中插入成员
int itype = 6;
mprWriteJson(json, “type”, sfmt("%d", itype), MPR_JSON_STRINGS);
3.讲json转换成字符串
char*buffer = mprJsonToString(json,MPR_JSON_QUOTES);
//js解析json的时候key要有“”,必须用MPR_JSON_QUOTES
不需要去释放,自动的。
下面是一些可能会用到的宏。
/******************************** JSON ****************************************/
/*
Flags for mprJsonToString
*/
#define MPR_JSON_PRETTY 0x1 /**< Serialize output in a more human readable, multiline "pretty" format */
#define MPR_JSON_QUOTES 0x2 /**< Serialize output quoting keys */
#define MPR_JSON_STRINGS 0x4 /**< Emit all values as quoted strings */
/*
Data types for obj property values
*/
#define MPR_JSON_OBJ 0x1 /**< The property is an object */
#define MPR_JSON_ARRAY 0x2 /**< The property is an array */
#define MPR_JSON_VALUE 0x4 /**< The property is a value (false|true|null|undefined|regexp|number|string) */
#define MPR_JSON_FALSE 0x8 /**< The property is false. MPR_JSON_VALUE also set. */
#define MPR_JSON_NULL 0x10 /**< The property is null. MPR_JSON_VALUE also set. */
#define MPR_JSON_NUMBER 0x20 /**< The property is a number. MPR_JSON_VALUE also set. */
#define MPR_JSON_REGEXP 0x40 /**< The property is a regular expression. MPR_JSON_VALUE also set. */
#define MPR_JSON_STRING 0x80 /**< The property is a string. MPR_JSON_VALUE also set. */
#define MPR_JSON_TRUE 0x100 /**< The property is true. MPR_JSON_VALUE also set. */
#define MPR_JSON_UNDEFINED 0x200 /**< The property is undefined. MPR_JSON_VALUE also set. */
#define MPR_JSON_OBJ_TYPE 0x7 /**< Mask for core type of obj (obj|array|value) */
#define MPR_JSON_DATA_TYPE 0xFF8 /**< Mask for core type of obj (obj|array|value) */
#define MPR_JSON_STATE_EOF 1 /* End of input */
#define MPR_JSON_STATE_ERR 2 /* Some parse error */
#define MPR_JSON_STATE_NAME 3 /* Expecting a name: */
#define MPR_JSON_STATE_VALUE 4 /* Expecting a value */
appweb后面还会继续使用,但应该就不会再更新了。这5篇文章足够把appweb搭建起来,一切都得靠自己。希望对读者有用。