在http://www.json.org/JSON_checker/上有一個開源的工具,僅一個C文件、一個H文件,還附帶UTF8轉UTF16的轉換工具。
將main函數修改了一下,便可作爲工程的一個小模塊使用,檢查JSON字符串的合法性,以便於進行報文解析。
/*
Read input string and check.
if not json string return -1, else return 0.
jc will contain a JSON_checker with a maximum depth of 20.
*/
int json_checker(const char *json_str)
{
JSON_checker jc = new_JSON_checker(20);
int len = strlen(json_str);
int tmp_i = 0;
for (tmp_i = 0; tmp_i < len; tmp_i++)
{
int next_char = json_str[tmp_i];
if (next_char <= 0)
{
break;
}
if (0 == JSON_checker_char(jc, next_char))
{
fprintf(stderr, "JSON_checker_char: syntax error\n");
return -1;
}
}
if (0 == JSON_checker_done(jc))
{
fprintf(stderr, "JSON_checker_end: syntax error\n");
return -1;
}
return 0;
}
至此,該模塊已經可以檢測JSON字符串的合法性了,但是還是不支持中文字符,一旦輸入合法的保含中文的JSON字符串還是會報錯。
想了個簡單的辦法,將字符串中的中文字符全部以“*”替換掉,再進行合法性檢測,檢測通過,則可認爲字符串是JSON報文。
/**
* @function 將中文字符替換爲'*' 用於json字符串合法性檢查
* @ in json string
* @author super bert
*/
int replace_character(char *string)
{
if (string == NULL)
{
printf("No string buf...\n");
return -1;
}
while(*string++ != '\0')
{
if (((*string) < 0x00) || ((*string) > 0x7F))
{
*string = '*';
}
}
return 0;
}