我已经成功地使用json-c库和json_object_to_json_string(jobj)
创建了jobj
,其中jobj
保存json格式的数据。
我可以使用printf
在控制台上打印jobj
:printf ("%s",json_object_to_json_string(jobj));
现在我需要将CCD_ 7数据写入";C";语言为jobj
,我们声明为json_object * jobj = json_object_new_object();
请求提供上述信息,即将jobj
写入文件(fwrite(。
下面是代码狙击手的示例https://linuxprograms.wordpress.com/2010/08/19/json_object_new_array/
下面是代码狙击手
static void prepared_line_file(char* line)
{
FILE* fptr;
fptr = fopen("/home/ubuntu/Desktop/sample.json", "a")
fwrite(line,sizeof(char),strlen(line),logfile);
}
main()
{
json_object_object_add(jobj,"USER", jarray);
prepared_line_file(jobj);
}
我错过什么了吗?
我稍微修改了您给出的代码,以便将表示json对象的可读字符串写入文件。
static void prepared_line_file(char* line)
{
FILE* fptr;
fptr = fopen("/home/ubuntu/Desktop/sample.json", "a");
fwrite(line,sizeof(char),strlen(line),fptr);
// fprintf(fptr, "%s", line); // would work too
// The file should be closed when everything is written
fclose(fptr);
}
main()
{
// Will hold the string representation of the json object
char *serialized_json;
// Create an empty object : {}
json_object * jobj = json_object_new_object();
// Create an empty array : []
json_object *jarray = json_object_new_array();
// Put the array into the object : { "USER" : [] }
json_object_object_add(jobj,"USER", jarray);
// Transforms the binary representation into a string representation
serialized_json = json_object_to_json_string(jobj);
prepared_line_file(serialized_json);
// Reports to the caller that everything was OK
return EXIT_SUCCESS;
}