在使用C語(yǔ)言中進(jìn)行json輸出時(shí),有時(shí)會(huì)碰到輸出亂碼的現(xiàn)象,這是因?yàn)镃語(yǔ)言默認(rèn)使用ASCII編碼,而json使用的是UTF-8編碼。
json_object * jobj = json_object_new_object(); json_object * jstr = json_object_new_string("你好"); json_object_object_add(jobj,"greeting", jstr); printf("%s\n", json_object_to_json_string(jobj));
以上代碼中,當(dāng)使用printf輸出json字符串時(shí),中文會(huì)出現(xiàn)亂碼。這是因?yàn)閜rintf函數(shù)默認(rèn)將中文按照ASCII編碼輸出,導(dǎo)致輸出結(jié)果出現(xiàn)亂碼。
解決方法是將輸出格式化為UTF-8編碼,可以使用iconv庫(kù)實(shí)現(xiàn)。
json_object * jobj = json_object_new_object(); json_object * jstr = json_object_new_string("你好"); json_object_object_add(jobj,"greeting", jstr); char *utf8_str = json_object_to_json_string(jobj); iconv_t iconv_handle = iconv_open("UTF-8", "ASCII"); size_t inbytesleft = strlen(utf8_str); size_t outbytesleft = inbytesleft * 4; char *outbuf = malloc(outbytesleft); memset(outbuf, 0, outbytesleft); char *inbuf = utf8_str; char *tmp = outbuf; iconv(iconv_handle, &inbuf, &inbytesleft, &tmp, &outbytesleft); printf("%s\n", outbuf); iconv_close(iconv_handle); free(outbuf);
以上代碼使用iconv將ASCII編碼的字符串轉(zhuǎn)換為UTF-8編碼字符串,最終實(shí)現(xiàn)了正確輸出中文的json字符串。