“文档” 菜单
文档首页
/ / /
C 驱动程序
/ /

创建 BSON 文档

在此页面上

  • bson_t 结构
  • 子文档和子数组
  • 简化 BSON C 对象表示法

BSON 文档是使用 bson_t 结构。此结构体封装了使用 BSON 规范 进行编码所需的逻辑 。 bson_t 的核心是 是一个缓冲区管理器和一组编码例程。

提示

根据性能需求或使用者的偏好,BSON 文档可以驻留在堆栈或堆上。

让我们首先在堆栈上创建一个新的 BSON 文档。 每当使用 libbson 时,请确保 #include <bson/bson.h>

bson_t b;
bson_init (&b);

这将创建一个空文档。 在 JSON 中,这与{}相同。

我们现在可以继续向 BSON 文档添加项目。根据要附加的字段类型,可以使用各种以bson_append_为前缀的函数。让我们附加一个 UTF- 8编码的字符串。

bson_append_utf8 (&b, "key", -1, "value", -1);

请注意两个-1参数。 第一个指示应使用strlen()确定key的长度(以字节为单位)。 或者,我们也可以传递数字3 。 这同样适用于第二个-1 ,但针对的是value

Libbson 提供了宏,以便在使用string字面量时简化此操作。 以下两个追加是相同的。

bson_append_utf8 (&b, "key", -1, "value", -1);
BSON_APPEND_UTF8 (&b, "key", "value");

现在让我们看一个向 BSON 文档添加几种不同字段类型的示例。

bson_t b = BSON_INITIALIZER;
BSON_APPEND_INT32 (&b, "a", 1);
BSON_APPEND_UTF8 (&b, "hello", "world");
BSON_APPEND_BOOL (&b, "bool", true);

请注意,我们省略了对 bson_init 的调用 。通过指定BSON_INITIALIZER ,我们无需将结构体初始化为基本状态。

简化子文档的创建 bson_append_document_begin 可用于使用父文档的内存区域作为目标缓冲区来构建子文档。

bson_t parent = BSON_INITIALIZER;
bson_t child;
bson_append_document_begin (&parent, "foo", 3, &child);
bson_append_int32 (&child, "baz", 3, 1);
bson_append_document_end (&parent, &child);
char *str = bson_as_relaxed_extended_json (&parent, NULL);
printf ("%s\n", str); // Prints: { "foo" : { "baz" : 1 } }
bson_free (str);
bson_destroy (&parent);

简化子数组的创建 bson_array_builder_t 可用于使用父数组的内存区域作为目标缓冲区来构建子数组。

bson_t parent = BSON_INITIALIZER;
bson_array_builder_t *bab;
bson_append_array_builder_begin (&parent, "foo", 3, &bab);
bson_array_builder_append_int32 (bab, 9);
bson_array_builder_append_int32 (bab, 8);
bson_array_builder_append_int32 (bab, 7);
bson_append_array_builder_end (&parent, bab);
char *str = bson_as_relaxed_extended_json (&parent, NULL);
printf ("%s\n", str); // Prints: { "foo" : [ 9, 8, 7 ] }
bson_free (str);
bson_destroy (&parent);

手动创建 BSON 文档既繁琐又耗时。添加了 BCON(即 BSON C 对象表示法),以允许以看起来更接近目标格式的格式创建 BSON 文档。

以下示例显示了 BCON 的用法。 请注意,字段值包装在BCON_*宏中。 这些是可变参数处理器确定参数类型所必需的。

bson_t *doc;
doc = BCON_NEW ("foo",
"{",
"int",
BCON_INT32 (1),
"array",
"[",
BCON_INT32 (100),
"{",
"sub",
BCON_UTF8 ("value"),
"}",
"]",
"}");

创建以下文档

{ "foo" : { "int" : 1, "array" : [ 100, { "sub" : "value" } ] } }

后退

在 C 程序中使用 libbson

来年

处理错误