CGI程式學習(4)-C程式中JSON解析
阿新 • • 發佈:2019-01-24
C程式中資料封裝和解析也可以用到JSON,不過需要額外新增json.h庫
#include <json/json.h> //用於儲存資料 int array_number; char wifiname_user[100][100]; char encryption_user[100][100]; char signal_user[100][100]; char channel_user[100][100]; //解析json函式 int AnalyJson(char *data); //修剪string函式 char *PruneString(char *Pstr); int main() { int status = AnalyJson(String); if(status != 0) { printf("Can't Json!"); return -1; } for(j = 0;j < array_number;j++) { printf("%s",wifiname_user[j]); } return 0; }
int AnalyJson(char *data) { // printf("data is %s\n\n",data); //json資料集 struct json_object *new_obj = NULL; //data資料域 struct json_object *obj_array = NULL; //每一條資料 struct json_object *array_string = NULL; //鍵值key struct json_object *string_wifiname , *string_encryption , *int_signal , *int_channel; //陣列個數計數 int i; //資料集長度 int len = strlen(data); //修剪字串 char prune_wifiname[100] = {0}; char prune_encryption[100] = {0}; //char wifiname_str[100] = {0}; //判斷資料長度,不符合長度,當錯誤資料處理 if (len > 10) { //判斷資料是否完整 //if((data[0] == '{') && (data[len-1] == '}')) if(data[0] == '{') { //將資料集轉json格式 new_obj = json_tokener_parse(data); //判斷json格式是否正確 if (is_error(new_obj)) { printf("json格式錯誤!\n"); //釋放new_obj json_object_put(new_obj); } else { //獲得key為name的值 obj_array = json_object_object_get(new_obj,"data"); //列印json_object型別 //printf("data = %s\n",json_object_to_json_string(obj_array)); //陣列個數 array_number = json_object_array_length(obj_array); //printf("length = %d\n",array_number); //迴圈解析 for (i = 0 ; i < array_number ; i++) { //取出每一條資料 array_string = json_object_array_get_idx(obj_array,i); //printf("string_array %d is %s\n",i,json_object_to_json_string(array_string)); //取鍵值對 string_wifiname = json_object_object_get(array_string,"wifiname"); string_encryption = json_object_object_get(array_string,"encryption"); int_signal = json_object_object_get(array_string,"signal"); int_channel = json_object_object_get(array_string,"channel"); //寫入陣列中,儲存全域性 sprintf(prune_wifiname,"%s",json_object_to_json_string(string_wifiname)); sprintf(prune_encryption,"%s",json_object_to_json_string(string_encryption)); sprintf(wifiname_user[i],"%s",PruneString(prune_wifiname)); sprintf(encryption_user[i],"%s",PruneString(prune_encryption)); sprintf(signal_user[i],"%s",json_object_to_json_string(int_signal)); sprintf(channel_user[i],"%s",json_object_to_json_string(int_channel)); json_object_put(array_string); } //釋放資料集 json_object_put(obj_array); json_object_put(new_obj); } } else { printf("資料不完整!\n"); return -1; } } else { printf("資料大小錯誤!\n"); return -1; } return 0; } char *PruneString(char *Pstr) { char *wifiname_str = (char *)malloc(100); int str_len = strlen(Pstr); int j; for (j = 0 ; j < str_len ; j++) { wifiname_str[j] = Pstr[j + 1]; } wifiname_str[str_len - 2] = '\0'; // printf("%s len = %d -> %s\n",Pstr,str_len,wifiname_str); return wifiname_str; }