json_object_object_add 可以替换现有条目吗?

标签 c json-c

Json-C 的引用计数笨拙且缺乏记录,这给我们带来了问题。特别是,我们有一个包含子对象的对象,并且想要用

替换特定的子对象

json_object_object_add(parent, "子名称", 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 - 我在与 JSON-C 静态库链接的编译器选项中缺少什么?

c++ - 段错误读取json文件

c++ - 由围绕矩形顺时针方向移动的数字组成的图案(长度和宽度每次都减小)

c - 奇偶查找表生成

如果在 c 中的结构内定义,枚举的范围是否有限

c - 如何清理由 "json_object_new_string"创建的 json 对象?

c - C语言中有效的json检查

c - printf (_ ("hello, world\n")) 是什么意思?

使用 pthreads 在多线程代码中计数器值意外更改