cJONS序列化工具解读二(数据解析)
cJSON數據解析
關于數據解析部分,其實這個解析就是個自動機,通過遞歸或者解析棧進行實現數據的解析
/* Utility to jump whitespace and cr/lf *///用于跳過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 *///根據前幾個字符設置c類型并更新讀取位置為endend = parse_value(c, skip(value));if (!end){ cJSON_Delete(c); //解析失敗,數據不完整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); }
①關于重點部分parse_value 對類型解讀函數
/* Parser core - when encountering text, process appropriately. *///將輸入字符串解析為具體類型cJSON結構 static const char *parse_value(cJSON *item, const char *value) {if (!value) return 0; /* Fail on null. */
//設置結構的具體類型并且返回下一個將要解讀數據的位置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. */ }
②解析字符串部分
解析字符串時, 對于特殊字符也應該轉義,比如 "n" 字符應該轉換為 'n' 這個換行符。
當然,如果只有特殊字符轉換的話,代碼不會又這么長, 對于字符串, 還要支持非 ascii 碼的字符, 即 utf8字符。
這些字符在字符串中會編碼為 uXXXX 的字符串, 我們現在需要還原為 0 - 255 的一個字符。
關于具體的字符解析中的編碼相關問題,請自行閱讀編碼相關知識?
③數字解析
/* 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; }④解析數組
解析數組, 需要先遇到 '[' 這個符號, 然后挨個的讀取節點內容, 節點使用 ',' 分隔, ',' 前后還可能有空格, 最后以 ']' 結尾。
我們要編寫的也是這樣。
先創建一個數組對象, 判斷是否有兒子, 有的話讀取第一個兒子, 然后判斷是不是有 逗號, 有的話循環讀取后面的兒子。
最后讀取 ']' 即可。
⑤解析對象
解析對象和解析數組類似, 只不過對象的一個兒子是個 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; }這樣都實現后, 字符串解析為 json 對象就實現了。
⑥序列化
序列化也就是格式化輸出了。
序列化又分為格式化輸出,壓縮輸出
?
/* 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; }?
假設我們要使用格式化輸出, 也就是美化輸出。
cjson 的做法不是邊分析 json 邊輸出, 而是預先將要輸的內容全部按字符串存在內存中, 最后輸出整個字符串。
這對于比較大的 json 來說, 內存就是個問題了。
另外,格式化輸出依靠的是節點的深度, 這個也可以優化, 一般寬度超過80 時, 就需要從新的一行算起的。
/* 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; }?
轉載于:https://www.cnblogs.com/lang5230/p/5492702.html
總結
以上是生活随笔為你收集整理的cJONS序列化工具解读二(数据解析)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于UNet和camvid数据集的道路分
- 下一篇: 微信小程序模板消息推送