Json-C 有这种笨拙且文档不足的引用计数,这给我们带来了问题。特别是,我们有一个包含 child 的对象,并希望用
替换特定的 childjson_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/