2016-04-19 19 views
1

Json-C有這種笨拙和文檔記錄不完善的引用計數,這給我們帶來了問題。特別是,我們有一個包含孩子的對象,並且想要用一個特定的孩子替換json_object_object_add是否可以替換現有條目?

json_object_object_add(parent, "child name", new_child)

現在我們知道這個轉讓歸屬new_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是足夠聰明,使前三個步驟是多餘的。這將是一個更好的設計,因爲我們更喜歡原子替換 - 如果新的孩子無論出於何種原因都不能添加,我們應該保留原來的孩子。

回答

1

在版本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; 
} 
相關問題