cJONS序列化工具解读二(数据解析)
cJSON數(shù)據(jù)解析
關(guān)于數(shù)據(jù)解析部分,其實(shí)這個(gè)解析就是個(gè)自動(dòng)機(jī),通過(guò)遞歸或者解析棧進(jìn)行實(shí)現(xiàn)數(shù)據(jù)的解析
/* Utility to jump whitespace and cr/lf *///用于跳過(guò)ascii小于32的空白字符 static const char *skip(const char *in) { while (in && *in && (unsigned char)*in <= 32)in++;return in; }/* Parse an object - create a new root, and populate. */ cJSON *cJSON_ParseWithOpts(const char *value, const char **return_parse_end, int require_null_terminated) {const char *end = 0;cJSON *c = cJSON_New_Item();ep = 0;if (!c) return 0; /* memory fail *///根據(jù)前幾個(gè)字符設(shè)置c類型并更新讀取位置為endend = parse_value(c, skip(value));if (!end){ cJSON_Delete(c); //解析失敗,數(shù)據(jù)不完整return 0; } /* parse failure. ep is set. *//* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */if (require_null_terminated)///??{ end = skip(end); if (*end){ cJSON_Delete(c); ep = end; return 0;}}if (return_parse_end)*return_parse_end = end;return c; } /* Default options for cJSON_Parse */ cJSON *cJSON_Parse(const char *value) { return cJSON_ParseWithOpts(value, 0, 0); }
①關(guān)于重點(diǎn)部分parse_value 對(duì)類型解讀函數(shù)
/* Parser core - when encountering text, process appropriately. *///將輸入字符串解析為具體類型cJSON結(jié)構(gòu) static const char *parse_value(cJSON *item, const char *value) {if (!value) return 0; /* Fail on null. */
//設(shè)置結(jié)構(gòu)的具體類型并且返回下一個(gè)將要解讀數(shù)據(jù)的位置if (!strncmp(value, "null", 4)) { item->type = cJSON_NULL; return value + 4; }if (!strncmp(value, "false", 5)) { item->type = cJSON_False; return value + 5; }if (!strncmp(value, "true", 4)) { item->type = cJSON_True; item->valueint = 1; return value + 4; }if (*value == '\"') { return parse_string(item, value); }if (*value == '-' || (*value >= '0' && *value <= '9')) { return parse_number(item, value); }if (*value == '[') { return parse_array(item, value); }if (*value == '{') { return parse_object(item, value); }ep = value; return 0; /* failure. */ }
②解析字符串部分
解析字符串時(shí), 對(duì)于特殊字符也應(yīng)該轉(zhuǎn)義,比如 "n" 字符應(yīng)該轉(zhuǎn)換為 'n' 這個(gè)換行符。
當(dāng)然,如果只有特殊字符轉(zhuǎn)換的話,代碼不會(huì)又這么長(zhǎng), 對(duì)于字符串, 還要支持非 ascii 碼的字符, 即 utf8字符。
這些字符在字符串中會(huì)編碼為 uXXXX 的字符串, 我們現(xiàn)在需要還原為 0 - 255 的一個(gè)字符。
關(guān)于具體的字符解析中的編碼相關(guān)問(wèn)題,請(qǐng)自行閱讀編碼相關(guān)知識(shí)?
③數(shù)字解析
/* Parse the input text to generate a number, and populate the result into item. */ static const char *parse_number(cJSON *item, const char *num) {double n = 0, sign = 1, scale = 0; int subscale = 0,signsubscale = 1;if (*num == '-')sign = -1, num++; /* Has sign? */if (*num == '0') num++; /* is zero */if (*num >= '1' && *num <= '9') do {n = (n*10.0) + (*num++ - '0');}while (*num >= '0' && *num <= '9'); /* Number? */if (*num == '.' && num[1] >= '0' && num[1] <= '9'){ num++; don = (n*10.0) + (*num++ - '0'), scale--;while (*num >= '0' && *num <= '9'); } /* Fractional part? */if (*num == 'e' || *num == 'E') /* Exponent? */{num++;if (*num == '+')num++; else if (*num == '-')signsubscale = -1, num++; /* With sign? */while (*num >= '0' && *num <= '9')subscale = (subscale * 10) + (*num++ - '0'); /* Number? */}n = sign*n*pow(10.0, (scale + subscale*signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */item->valuedouble = n;item->valueint = (int)n;item->type = cJSON_Number;return num; }④解析數(shù)組
解析數(shù)組, 需要先遇到 '[' 這個(gè)符號(hào), 然后挨個(gè)的讀取節(jié)點(diǎn)內(nèi)容, 節(jié)點(diǎn)使用 ',' 分隔, ',' 前后還可能有空格, 最后以 ']' 結(jié)尾。
我們要編寫的也是這樣。
先創(chuàng)建一個(gè)數(shù)組對(duì)象, 判斷是否有兒子, 有的話讀取第一個(gè)兒子, 然后判斷是不是有 逗號(hào), 有的話循環(huán)讀取后面的兒子。
最后讀取 ']' 即可。
⑤解析對(duì)象
解析對(duì)象和解析數(shù)組類似, 只不過(guò)對(duì)象的一個(gè)兒子是個(gè) key - value, key 是字符串, value 可能是任何值, key 和 value 用 ":" 分隔。
/* Render an object to text. */ static char *print_object(cJSON *item, int depth, int fmt, printbuffer *p) {char **entries = 0, **names = 0;char *out = 0, *ptr, *ret, *str; int len = 7, i = 0, j;cJSON *child = item->child;int numentries = 0, fail = 0;size_t tmplen = 0;/* Count the number of entries. */while (child) numentries++, child = child->next;/* Explicitly handle empty object case */if (!numentries){if (p) out = ensure(p, fmt ? depth + 4 : 3);else out = (char*)cJSON_malloc(fmt ? depth + 4 : 3);if (!out) return 0;ptr = out; *ptr++ = '{';if (fmt) { *ptr++ = '\n'; for (i = 0; i<depth - 1; i++) *ptr++ = '\t'; }*ptr++ = '}'; *ptr++ = 0;return out;}if (p){/* Compose the output: */i = p->offset;len = fmt ? 2 : 1; ptr = ensure(p, len + 1); if (!ptr) return 0;*ptr++ = '{'; if (fmt) *ptr++ = '\n'; *ptr = 0; p->offset += len;child = item->child; depth++;while (child){if (fmt){ptr = ensure(p, depth); if (!ptr) return 0;for (j = 0; j<depth; j++) *ptr++ = '\t';p->offset += depth;}print_string_ptr(child->string, p);p->offset = update(p);len = fmt ? 2 : 1;ptr = ensure(p, len); if (!ptr) return 0;*ptr++ = ':'; if (fmt) *ptr++ = '\t';p->offset += len;print_value(child, depth, fmt, p);p->offset = update(p);len = (fmt ? 1 : 0) + (child->next ? 1 : 0);ptr = ensure(p, len + 1); if (!ptr) return 0;if (child->next) *ptr++ = ',';if (fmt) *ptr++ = '\n'; *ptr = 0;p->offset += len;child = child->next;}ptr = ensure(p, fmt ? (depth + 1) : 2); if (!ptr) return 0;if (fmt) for (i = 0; i<depth - 1; i++) *ptr++ = '\t';*ptr++ = '}'; *ptr = 0;out = (p->buffer) + i;}else{/* Allocate space for the names and the objects */entries = (char**)cJSON_malloc(numentries * sizeof(char*));if (!entries) return 0;names = (char**)cJSON_malloc(numentries * sizeof(char*));if (!names) { cJSON_free(entries); return 0; }memset(entries, 0, sizeof(char*)*numentries);memset(names, 0, sizeof(char*)*numentries);/* Collect all the results into our arrays: */child = item->child; depth++; if (fmt) len += depth;while (child){names[i] = str = print_string_ptr(child->string, 0);entries[i++] = ret = print_value(child, depth, fmt, 0);if (str && ret) len += strlen(ret) + strlen(str) + 2 + (fmt ? 2 + depth : 0); else fail = 1;child = child->next;}/* Try to allocate the output string */if (!fail) out = (char*)cJSON_malloc(len);if (!out) fail = 1;/* Handle failure */if (fail){for (i = 0; i<numentries; i++) { if (names[i]) cJSON_free(names[i]); if (entries[i]) cJSON_free(entries[i]); }cJSON_free(names); cJSON_free(entries);return 0;}/* Compose the output: */*out = '{'; ptr = out + 1; if (fmt)*ptr++ = '\n'; *ptr = 0;for (i = 0; i<numentries; i++){if (fmt) for (j = 0; j<depth; j++) *ptr++ = '\t';tmplen = strlen(names[i]); memcpy(ptr, names[i], tmplen); ptr += tmplen;*ptr++ = ':'; if (fmt) *ptr++ = '\t';strcpy(ptr, entries[i]); ptr += strlen(entries[i]);if (i != numentries - 1) *ptr++ = ',';if (fmt) *ptr++ = '\n'; *ptr = 0;cJSON_free(names[i]); cJSON_free(entries[i]);}cJSON_free(names); cJSON_free(entries);if (fmt) for (i = 0; i<depth - 1; i++) *ptr++ = '\t';*ptr++ = '}'; *ptr++ = 0;}return out; }這樣都實(shí)現(xiàn)后, 字符串解析為 json 對(duì)象就實(shí)現(xiàn)了。
⑥序列化
序列化也就是格式化輸出了。
序列化又分為格式化輸出,壓縮輸出
?
/* Render a cJSON item/entity/structure to text. */ char *cJSON_Print(cJSON *item) { return print_value(item, 0, 1, 0); } char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item, 0, 0, 0); }char *cJSON_PrintBuffered(cJSON *item, int prebuffer, int fmt) {printbuffer p;p.buffer = (char*)cJSON_malloc(prebuffer);p.length = prebuffer;p.offset = 0;return print_value(item, 0, fmt, &p);return p.buffer; }/* Render a value to text. */ static char *print_value(cJSON *item, int depth, int fmt, printbuffer *p) {char *out = 0;if (!item) return 0;if (p){switch ((item->type) & 255){case cJSON_NULL: {out = ensure(p, 5); if (out) strcpy(out, "null"); break; }case cJSON_False: {out = ensure(p, 6); if (out) strcpy(out, "false"); break; }case cJSON_True: {out = ensure(p, 5); if (out) strcpy(out, "true"); break; }case cJSON_Number: out = print_number(item, p); break;case cJSON_String: out = print_string(item, p); break;case cJSON_Array: out = print_array(item, depth, fmt, p); break;case cJSON_Object: out = print_object(item, depth, fmt, p); break;}}else{switch ((item->type) & 255){case cJSON_NULL: out = cJSON_strdup("null"); break;case cJSON_False: out = cJSON_strdup("false"); break;case cJSON_True: out = cJSON_strdup("true"); break;case cJSON_Number: out = print_number(item, 0); break;case cJSON_String: out = print_string(item, 0); break;case cJSON_Array: out = print_array(item, depth, fmt, 0); break;case cJSON_Object: out = print_object(item, depth, fmt, 0); break;}}return out; }?
假設(shè)我們要使用格式化輸出, 也就是美化輸出。
cjson 的做法不是邊分析 json 邊輸出, 而是預(yù)先將要輸?shù)膬?nèi)容全部按字符串存在內(nèi)存中, 最后輸出整個(gè)字符串。
這對(duì)于比較大的 json 來(lái)說(shuō), 內(nèi)存就是個(gè)問(wèn)題了。
另外,格式化輸出依靠的是節(jié)點(diǎn)的深度, 這個(gè)也可以優(yōu)化, 一般寬度超過(guò)80 時(shí), 就需要從新的一行算起的。
/* Render an object to text. */ static char *print_object(cJSON *item, int depth, int fmt, printbuffer *p) {char **entries = 0, **names = 0;char *out = 0, *ptr, *ret, *str; int len = 7, i = 0, j;cJSON *child = item->child;int numentries = 0, fail = 0;size_t tmplen = 0;/* Count the number of entries. */while (child) numentries++, child = child->next;/* Explicitly handle empty object case */if (!numentries){if (p) out = ensure(p, fmt ? depth + 4 : 3);else out = (char*)cJSON_malloc(fmt ? depth + 4 : 3);if (!out) return 0;ptr = out; *ptr++ = '{';if (fmt) { *ptr++ = '\n'; for (i = 0; i<depth - 1; i++) *ptr++ = '\t'; }*ptr++ = '}'; *ptr++ = 0;return out;}if (p){/* Compose the output: */i = p->offset;len = fmt ? 2 : 1; ptr = ensure(p, len + 1); if (!ptr) return 0;*ptr++ = '{'; if (fmt) *ptr++ = '\n'; *ptr = 0; p->offset += len;child = item->child; depth++;while (child){if (fmt){ptr = ensure(p, depth); if (!ptr) return 0;for (j = 0; j<depth; j++) *ptr++ = '\t';p->offset += depth;}print_string_ptr(child->string, p);p->offset = update(p);len = fmt ? 2 : 1;ptr = ensure(p, len); if (!ptr) return 0;*ptr++ = ':'; if (fmt) *ptr++ = '\t';p->offset += len;print_value(child, depth, fmt, p);p->offset = update(p);len = (fmt ? 1 : 0) + (child->next ? 1 : 0);ptr = ensure(p, len + 1); if (!ptr) return 0;if (child->next) *ptr++ = ',';if (fmt) *ptr++ = '\n'; *ptr = 0;p->offset += len;child = child->next;}ptr = ensure(p, fmt ? (depth + 1) : 2); if (!ptr) return 0;if (fmt) for (i = 0; i<depth - 1; i++) *ptr++ = '\t';*ptr++ = '}'; *ptr = 0;out = (p->buffer) + i;}else{/* Allocate space for the names and the objects */entries = (char**)cJSON_malloc(numentries * sizeof(char*));if (!entries) return 0;names = (char**)cJSON_malloc(numentries * sizeof(char*));if (!names) { cJSON_free(entries); return 0; }memset(entries, 0, sizeof(char*)*numentries);memset(names, 0, sizeof(char*)*numentries);/* Collect all the results into our arrays: */child = item->child; depth++; if (fmt) len += depth;while (child){names[i] = str = print_string_ptr(child->string, 0);entries[i++] = ret = print_value(child, depth, fmt, 0);if (str && ret) len += strlen(ret) + strlen(str) + 2 + (fmt ? 2 + depth : 0); else fail = 1;child = child->next;}/* Try to allocate the output string */if (!fail) out = (char*)cJSON_malloc(len);if (!out) fail = 1;/* Handle failure */if (fail){for (i = 0; i<numentries; i++) { if (names[i]) cJSON_free(names[i]); if (entries[i]) cJSON_free(entries[i]); }cJSON_free(names); cJSON_free(entries);return 0;}/* Compose the output: */*out = '{'; ptr = out + 1; if (fmt)*ptr++ = '\n'; *ptr = 0;for (i = 0; i<numentries; i++){if (fmt) for (j = 0; j<depth; j++) *ptr++ = '\t';tmplen = strlen(names[i]); memcpy(ptr, names[i], tmplen); ptr += tmplen;*ptr++ = ':'; if (fmt) *ptr++ = '\t';strcpy(ptr, entries[i]); ptr += strlen(entries[i]);if (i != numentries - 1) *ptr++ = ',';if (fmt) *ptr++ = '\n'; *ptr = 0;cJSON_free(names[i]); cJSON_free(entries[i]);}cJSON_free(names); cJSON_free(entries);if (fmt) for (i = 0; i<depth - 1; i++) *ptr++ = '\t';*ptr++ = '}'; *ptr++ = 0;}return out; }?
static char *print_array(cJSON *item, int depth, int fmt, printbuffer *p) {char **entries;char *out = 0, *ptr, *ret; int len = 5;cJSON *child = item->child;int numentries = 0, i = 0, fail = 0;size_t tmplen = 0;/* How many entries in the array? */while (child) numentries++, child = child->next;/* Explicitly handle numentries==0 */if (!numentries){if (p) out = ensure(p, 3);else out = (char*)cJSON_malloc(3);if (out) strcpy(out, "[]");return out;}if (p){/* Compose the output array. */i = p->offset;ptr = ensure(p, 1); if (!ptr) return 0; *ptr = '['; p->offset++;child = item->child;while (child && !fail){print_value(child, depth + 1, fmt, p);p->offset = update(p);if (child->next) { len = fmt ? 2 : 1; ptr = ensure(p, len + 1); if (!ptr) return 0; *ptr++ = ','; if (fmt)*ptr++ = ' '; *ptr = 0; p->offset += len; }child = child->next;}ptr = ensure(p, 2); if (!ptr) return 0; *ptr++ = ']'; *ptr = 0;out = (p->buffer) + i;}else{/* Allocate an array to hold the values for each */entries = (char**)cJSON_malloc(numentries * sizeof(char*));if (!entries) return 0;memset(entries, 0, numentries * sizeof(char*));/* Retrieve all the results: */child = item->child;while (child && !fail){ret = print_value(child, depth + 1, fmt, 0);entries[i++] = ret;if (ret) len += strlen(ret) + 2 + (fmt ? 1 : 0); else fail = 1;child = child->next;}/* If we didn't fail, try to malloc the output string */if (!fail) out = (char*)cJSON_malloc(len);/* If that fails, we fail. */if (!out) fail = 1;/* Handle failure. */if (fail){for (i = 0; i<numentries; i++) if (entries[i]) cJSON_free(entries[i]);cJSON_free(entries);return 0;}/* Compose the output array. */*out = '[';ptr = out + 1; *ptr = 0;for (i = 0; i<numentries; i++){tmplen = strlen(entries[i]); memcpy(ptr, entries[i], tmplen); ptr += tmplen;if (i != numentries - 1) { *ptr++ = ','; if (fmt)*ptr++ = ' '; *ptr = 0; }cJSON_free(entries[i]);}cJSON_free(entries);*ptr++ = ']'; *ptr++ = 0;}return out; }?
轉(zhuǎn)載于:https://www.cnblogs.com/lang5230/p/5492702.html
總結(jié)
以上是生活随笔為你收集整理的cJONS序列化工具解读二(数据解析)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 基于UNet和camvid数据集的道路分
- 下一篇: 微信小程序模板消息推送