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/