我希望使用json-c库来转换 .json 文档中包含的所有对象:
{
"name": "mathieu",
"password": "def118e47a2f36b73805b01a5fa3f73b506b98166a929802338db6868e28d942",
"salt": "nXvtCQEqx8l1uNheIJLoO8VI7049vgIS",
"email": "mathieu@mail.com"
}
{
"name": "cesar",
"password": "487b36f3e5a3a74ec3bf2bf48cbc49cde249b08977d22394122c9d512d0e94b4",
"salt": "Q3QnWFZnLXg8217V1uLaBka6R3CZvCfl",
"email": "cesar@mail.com"
}
为了转换它们(目前我只想显示),我使用以下代码(我按照这个Youtube 视频中的说明进行操作):
#include <stdio.h>
#include <stdlib.h>
#include <json-c/json.h>
//#include "../../include/personnes.h"
//int parseMyJsonPersonne(){
int main(){
FILE* fichier = NULL;
char buffer[1024];
struct json_object *parsed_json;
struct json_object *name;
struct json_object *password;
struct json_object *salt;
struct json_object *email;
fichier = fopen("../../data/Personne.json", "r");
if (fichier != NULL) {
fread(buffer, 1024, 1, fichier);
}
else {
printf("Une ERREUR est survenue lors du chargement des différents comptes\n");
return 1;
}
fclose(fichier);
printf("buffer : %s\n", buffer);
parsed_json = json_tokener_parse(buffer);
json_object_object_get_ex(parsed_json, "name", &name);
json_object_object_get_ex(parsed_json, "password", &password);
json_object_object_get_ex(parsed_json, "salt", &salt);
json_object_object_get_ex(parsed_json, "email", &email);
printf("name : %s\n", json_object_get_string(name));
printf("password : %s\n", json_object_get_string(password));
printf("salt : %s\n", json_object_get_string(salt));
printf("email : %s\n", json_object_get_string(email));
json_object_object_get_ex(parsed_json, "name", &name);
printf("name 2 : %s\n", json_object_get_string(name));
free(name);
free(password);
free(salt);
free(email);
return 0;
}
这是编译和执行后终端向我显示的内容:
buffer : {
"name": "mathieu",
"password": "def118e47a2f36b73805b01a5fa3f73b506b98166a929802338db6868e28d942",
"salt": "nXvtCQEqx8l1uNheIJLoO8VI7049vgIS",
"email": "mathieu@mail.com"
}
{
"name": "cesar",
"password": "487b36f3e5a3a74ec3bf2bf48cbc49cde249b08977d22394122c9d512d0e94b4",
"salt": "Q3QnWFZnLXg8217V1uLaBka6R3CZvCfl",
"email": "cesar@mail.com"
}
name : mathieu
password : def118e47a2f36b73805b01a5fa3f73b506b98166a929802338db6868e28d942
salt : nXvtCQEqx8l1uNheIJLoO8VI7049vgIS
email : mathieu@mail.com
name 2 : mathieu
所以这是我的各种问题:
- 如何转到下一个对象并知道 .json 中的对象数量?
- 我认为如果对象数量太大,将缓冲区初始化为1024会导致问题,那么有没有办法让缓冲区一个一个地获取对象?
- 我有一种感觉,内存的释放不对,是我忘记了一些free吗?