日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

cJONS序列化工具解读二(数据解析)

發(fā)布時(shí)間:2023/12/10 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 cJONS序列化工具解读二(数据解析) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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è)字符。

static unsigned parse_hex4(const char *str) {unsigned h = 0;if (*str >= '0' && *str <= '9') h += (*str) - '0';else if (*str >= 'A' && *str <= 'F')h += 10 + (*str) - 'A';else if (*str >= 'a' && *str <= 'f')h += 10 + (*str) - 'a'; else return 0;h = h << 4; //*Fstr++;if (*str >= '0' && *str <= '9')h += (*str) - '0'; else if (*str >= 'A' && *str <= 'F')h += 10 + (*str) - 'A'; else if (*str >= 'a' && *str <= 'f') h += 10 + (*str) - 'a'; elsereturn 0;h = h << 4;str++;if (*str >= '0' && *str <= '9')h += (*str) - '0'; else if (*str >= 'A' && *str <= 'F')h += 10 + (*str) - 'A';else if (*str >= 'a' && *str <= 'f')h += 10 + (*str) - 'a';else return 0;h = h << 4; str++;if (*str >= '0' && *str <= '9')h += (*str) - '0'; else if (*str >= 'A' && *str <= 'F')h += 10 + (*str) - 'A';else if (*str >= 'a' && *str <= 'f')h += 10 + (*str) - 'a'; else return 0;return h; }/* Parse the input text into an unescaped cstring, and populate item. */ static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; static const char *parse_string(cJSON *item, const char *str) {const char *ptr = str + 1;char *ptr2; char *out;int len = 0; unsigned uc, uc2;if (*str != '\"') { ep = str; return 0; } /* not a string! */while(*ptr != '\"' && *ptr && ++len)if (*ptr++ == '\\') //跳過(guò)\續(xù)行符ptr++; /* Skip escaped quotes. *///空間申請(qǐng)out = (char*)cJSON_malloc(len + 1); /* This is how long we need for the string, roughly. */if (!out) return 0;ptr = str + 1;//跳過(guò)“開(kāi)始ptr2 = out;while (*ptr != '\"' && *ptr){if (*ptr != '\\')*ptr2++ = *ptr++;else //轉(zhuǎn)義字符處理 {ptr++;switch (*ptr){case 'b': *ptr2++ = '\b'; break;case 'f': *ptr2++ = '\f'; break;case 'n': *ptr2++ = '\n'; break;case 'r': *ptr2++ = '\r'; break;case 't': *ptr2++ = '\t'; break;case 'u': /* transcode utf16 to utf8. */uc = parse_hex4(ptr + 1); ptr += 4; /* get the unicode char. */if ((uc >= 0xDC00 && uc <= 0xDFFF) || uc == 0) break; /* check for invalid. */if (uc >= 0xD800 && uc <= 0xDBFF) /* UTF16 surrogate pairs. */{if (ptr[1] != '\\' || ptr[2] != 'u') break; /* missing second-half of surrogate. */uc2 = parse_hex4(ptr + 3);ptr += 6;if (uc2<0xDC00 || uc2>0xDFFF) break; /* invalid second-half of surrogate. */uc = 0x10000 + (((uc & 0x3FF) << 10) | (uc2 & 0x3FF));}len = 4; if (uc<0x80)len = 1;else if (uc<0x800)len = 2; else if (uc<0x10000) len = 3;ptr2 += len;switch (len){case 4:*--ptr2 = ((uc | 0x80) & 0xBF); uc >>= 6;case 3:*--ptr2 = ((uc | 0x80) & 0xBF); uc >>= 6;case 2:*--ptr2 = ((uc | 0x80) & 0xBF); uc >>= 6;case 1:*--ptr2 = (uc | firstByteMark[len]);}ptr2 += len;break;default:*ptr2++ = *ptr; break;}ptr++;}}*ptr2 = 0;if (*ptr == '\"') ptr++;item->valuestring = out;item->type = cJSON_String;return ptr; }

關(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)讀取后面的兒子。
最后讀取 ']' 即可。


/* Build an array from input text. */ static const char *parse_array(cJSON *item, const char *value) {cJSON *child;if (*value != '[') {ep = value;return 0;} /* not an array! */item->type = cJSON_Array;value = skip(value + 1);if (*value == ']')return value + 1; /* empty array. */item->child = child = cJSON_New_Item();if (!item->child) return 0; /* memory fail *///解析數(shù)組內(nèi)結(jié)構(gòu)value = skip(parse_value(child, skip(value))); /* skip any spacing, get the value. */if (!value) return 0;while (*value == ','){cJSON *new_item;if (!(new_item = cJSON_New_Item())) return 0; /* memory fail */child->next = new_item; new_item->prev = child;child = new_item;value = skip(parse_value(child, skip(value + 1)));if (!value)return 0; /* memory fail */}if (*value == ']')return value + 1; /* end of array */ep = value; return 0; /* malformed. */ }

⑤解析對(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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。