1

我已经jobj通过使用 json-c 库成功创建了该库,json_object_to_json_string(jobj)其中jobj保存了 json 格式的数据。

我可以jobj使用以下命令在控制台上打印printfprintf ("%s",json_object_to_json_string(jobj));

现在我需要用我们声明jobj的“C”语言将数据写入文件jobjjson_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);
}

我错过了什么吗?

4

1 回答 1

0

我稍微修改了您提供的代码,以便将表示 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;
}
于 2022-01-21T06:49:18.923 回答