淘先锋技术网

首页 1 2 3 4 5 6 7

C List String 转 JSON

C 语言中没有内置的 JSON 库,需要手动编写实现。在将 C List 中的 String 转换成 JSON 格式时,需要注意以下几点:

1. JSON 格式规范

Json:
Object
Array
Object:
{}
Array:
[]
Value:
String
Number
Object
Array
true
false
null
String:
""
" chars "
Number:
int
int frac
int exp
int frac exp
chars:
char
char chars
char:
any-Unicode-character-
except-"-or-\-or-
control-character
\" / \\ / \/ / \b / \f / \n / \r / \t / \u four-hex-digits
int:
digit
digit1-9 digits
frac:
. digits
exp:
e digits
E digits
digits:
digit
digit1-9 digits

2. C List 转换成 JSON

char *list_to_json_string(List *list){
if(list == NULL){
return "{}";
}
int size = list_size(list);
if(size == 0){
return "[]";
}
char **elements = (char**)malloc(sizeof(char*) * size);
ListElement *current = list_head(list);
int i;
for(i = 0; i< size; i++){
elements[i] = (char*)current->data;
current = current->next;
}
char *json_str = join_strings(elements, size, ", ");
char *ret_str = (char*)malloc(sizeof(char) * (strlen(json_str) + 3));
ret_str[0] = '[';
strcpy(ret_str+1, json_str);
ret_str[strlen(json_str)+1] = ']';
ret_str[strlen(json_str)+2] = '\0';
free(elements);
free(json_str);
return ret_str;
}

3. join_strings 函数实现

char *join_strings(char **strings, int size, const char *delimiter){
int len = 0;
int i;
for(i = 0; i< size; i++){
len += strlen(strings[i]);
if(i< size-1){
len += strlen(delimiter);
}
}
char *merged = (char*)malloc(sizeof(char) * (len + 1));
merged[0] = '\0';
for(i = 0; i< size; i++){
strcat(merged, strings[i]);
if(i< size-1){
strcat(merged, delimiter);
}
}
return merged;
}