]> granicus.if.org Git - json-c/commitdiff
Add method 'json_object_to_json_string_length'
authorjobol <jose.bollo@iot.bzh>
Tue, 26 Jul 2016 17:22:25 +0000 (19:22 +0200)
committerJosé Bollo <jose.bollo@iot.bzh>
Wed, 27 Jul 2016 12:45:25 +0000 (14:45 +0200)
This new method allows to also
get the length of the generated string.

Fix #165

Change-Id: Iea91404027f143ca3d29a4c58d7c07ae53556110
Signed-off-by: José Bollo <jose.bollo@iot.bzh>
json_object.c
json_object.h

index 24cb7abdbef4d5b5a76dcaca05ab34161ebab5cd..29eb29d0167e74503bcae87c5958fb68010fdbcb 100644 (file)
@@ -295,20 +295,35 @@ void json_object_set_serializer(json_object *jso,
 
 /* extended conversion to string */
 
-const char* json_object_to_json_string_ext(struct json_object *jso, int flags)
+const char* json_object_to_json_string_length(struct json_object *jso, int flags, size_t *length)
 {
-       if (!jso)
-               return "null";
+       const char *r = NULL;
+       size_t s = 0;
 
-       if ((!jso->_pb) && !(jso->_pb = printbuf_new()))
-               return NULL;
+       if (!jso)
+       {
+               s = 4;
+               r = "null";
+       }
+       else if ((jso->_pb) || (jso->_pb = printbuf_new()))
+       {
+               printbuf_reset(jso->_pb);
 
-       printbuf_reset(jso->_pb);
+               if(jso->_to_json_string(jso, jso->_pb, 0, flags) >= 0)
+               {
+                       s = (size_t)jso->_pb->bpos;
+                       r = jso->_pb->buf;
+               }
+       }
 
-       if(jso->_to_json_string(jso, jso->_pb, 0, flags) < 0)
-               return NULL;
+       if (length)
+               *length = s;
+       return r;
+}
 
-       return jso->_pb->buf;
+const char* json_object_to_json_string_ext(struct json_object *jso, int flags)
+{
+       return json_object_to_json_string_length(jso, flags, NULL);
 }
 
 /* backwards-compatible conversion to string */
index 4bcfcbcca17697b4b8b15918011d251bc0a8a6bb..19afa5e2717900d12378a601fad71d4a94d51331 100644 (file)
@@ -223,6 +223,16 @@ extern const char* json_object_to_json_string(struct json_object *obj);
 extern const char* json_object_to_json_string_ext(struct json_object *obj, int
 flags);
 
+/** Stringify object to json format
+ * @see json_object_to_json_string() for details on how to free string.
+ * @param obj the json_object instance
+ * @param flags formatting options, see JSON_C_TO_STRING_PRETTY and other constants
+ * @param length a pointer where, if not NULL, the length (without null) is stored
+ * @returns a string in JSON format and the length if not NULL
+ */
+extern const char* json_object_to_json_string_length(struct json_object *obj, int
+flags, size_t *length);
+
 /**
  * Returns the userdata set by json_object_set_userdata() or
  * json_object_set_serializer()