]> git.feebdaed.xyz Git - 0xmirror/cJSON.git/commitdiff
add new function of setValuestringToObject
authorAlanscut <wp_scut@163.com>
Tue, 24 Mar 2020 14:28:15 +0000 (22:28 +0800)
committerAlanscut <wp_scut@163.com>
Tue, 24 Mar 2020 14:28:15 +0000 (22:28 +0800)
cJSON.c
cJSON.h

diff --git a/cJSON.c b/cJSON.c
index b0e744e42b357458ff2c05eca76b80d58760aa49..ff8d2b99460c9590991663de907123b235a4feba 100644 (file)
--- a/cJSON.c
+++ b/cJSON.c
@@ -368,6 +368,31 @@ CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number)
     return object->valuedouble = number;
 }
 
+CJSON_PUBLIC(char*) cJSON_SetValuestringToObject(cJSON *object, const char *valuestring)
+{
+    size_t length = 0;
+    char *copy = NULL;
+    /* if object->valuestring is NULL, it should not set valuestring */
+    if (object->valuestring == NULL)
+    {
+        return NULL;
+    }
+    length = strlen(valuestring) + sizeof("");
+    copy = (char*) cJSON_malloc(length);
+    if (copy == NULL)
+    {
+        return NULL;
+    }
+    memcpy(copy, valuestring, length);
+    if (!(object->type & cJSON_IsReference) && (object->valuestring != NULL))
+    {
+        cJSON_free(object->valuestring);
+    }
+    object->valuestring = copy;
+
+    return copy;
+}
+
 typedef struct
 {
     unsigned char *buffer;
diff --git a/cJSON.h b/cJSON.h
index 2c535628ae10ee5545e37d9326f2cead981d24e9..1455ece72c6af36fb65112960a83032aa786a1e0 100644 (file)
--- a/cJSON.h
+++ b/cJSON.h
@@ -278,6 +278,8 @@ CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * c
 /* helper for the cJSON_SetNumberValue macro */
 CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
 #define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
+/* Only takes effect when type of object is JSON_Object */
+CJSON_PUBLIC(char*) cJSON_SetValuestringToObject(cJSON *object, const char *valuestring);
 
 /* Macro for iterating over an array or object */
 #define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)