How to clean a json object created by “json_object_new_string”?

与世无争的帅哥 提交于 2019-12-04 03:58:30

问题


I have the following code and I want to clean a json object created by json_object_new_string().

#include <json/json.h>
#include <stdio.h>

int main() {
  /*Creating a json object*/
  json_object * jobj = json_object_new_object();

  /*Creating a json string*/
  json_object *jstring = json_object_new_string("Joys of Programming");


  /*Form the json object*/
  json_object_object_add(jobj,"Site Name", jstring);

  /*Now printing the json object*/
  printf ("The json object created: %sn",json_object_to_json_string(jobj));

  /* clean the json object */
  json_object_put(jobj);

}

Does the line json_object_put(jobj); clean both jobj and jstring ?

Or I have to a clean jstring alone with json_object_put(jstring);?

Edit

question2

what will be the behaviour if the jstring is creted into a function in this way?

#include <json/json.h>
#include <stdio.h>

static void my_json_add_obj(json_object *jobj, char *name, char *val) {
      /*Creating a json string*/
      json_object *jstring = json_object_new_string(val);


      /*Form the json object*/
      json_object_object_add(jobj,name, jstring);
}

int main() {
  /*Creating a json object*/
  json_object * jobj = json_object_new_object();

  my_json_add_obj(jobj, "Site Name", "Joys of Programming")

  /*Now printing the json object*/
  printf ("The json object created: %sn",json_object_to_json_string(jobj));

  /* clean the json object */
  json_object_put(jobj);

}

the jstring in this case is a local variable into a function. Does the json_object_put(jobj); will clean the jstring (created in the function my_json_add_obj()) ?


回答1:


json_object_put will free everything referenced by the object. So yes, it's sufficient to use that function on jobj to free the whole object.



来源:https://stackoverflow.com/questions/18382897/how-to-clean-a-json-object-created-by-json-object-new-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!