json_object_object_add 可以替换现有条目吗?

标签 c json-c

Json-C 有这种笨拙且文档不足的引用计数,这给我们带来了问题。特别是,我们有一个包含 child 的对象,并希望用

替换特定的 child

json_object_object_add(parent, "child name", new_child).

现在我们知道这转让 new_child 的所有权,这没问题。但是那个大 child 呢?我们可以使用 json_object_object_del 手动删除它,doesn't delete the old child (but leaks it) .所以看起来以下解决方案是一个合适的替代品:

json_object *manual = json_object_object_get(parent, "child name");
json_object_object_del(parent, "child name");
json_object_put(manual);
json_object_object_add(parent, "child name", new_child);

但是,我们想知道 json_object_object_add 是否足够聪明,可以让前三个步骤变得多余。这将是一个更好的设计,因为我们更喜欢原子替换——如果由于某种原因不能添加新的 child ,我们应该保留旧的 child 。

最佳答案

在 0.12 版本中,您不必这样做。该函数如下所示:

void json_object_object_add(struct json_object* jso, const char *key,
                struct json_object *val)
{
    // We lookup the entry and replace the value, rather than just deleting
    // and re-adding it, so the existing key remains valid.
    json_object *existing_value = NULL;
    struct lh_entry *existing_entry;
    existing_entry = lh_table_lookup_entry(jso->o.c_object, (void*)key);
    if (!existing_entry)
    {
        lh_table_insert(jso->o.c_object, strdup(key), val);
        return;
    }
    existing_value = (void *)existing_entry->v;
    if (existing_value)
        json_object_put(existing_value);
    existing_entry->v = val;
}

关于json_object_object_add 可以替换现有条目吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36720411/

相关文章:

C 如何检查数组是否已满?

用字符串数组替换字符串的 C 程序

C++ 指针加法被乘

c - 如何拆分多行字符串并将它们存储到C中的json数组中

c - C中的Json解析和字符串管理

c - 使用 json-c 解析深度嵌套的 JSON 键

c - 静态定义对性能、代码内存大小和数据内存大小的影响?

java - JNI : How to pass "unsigned char* " from C++ to java

macos - 将 JSON-C 添加到现有的 POSTGIS 安装

c - 在 C 中解析 JSON 数组