使用 jsonc 库在 C 中追加 json_object_arrays

Append json_object_arrays in C using jsonc library

我是C语言新手。我需要附加两个使用 json-c 库创建的 json_object 数组。这是我的代码:

struct json_object *obj1,*array1,*array2,*array3;

obj1 = json_object_new_object();    

array1 = json_object_new_array();
json_object_array_add(array1, json_object_new_int(1));
json_object_array_add(array1, json_object_new_int(2));
json_object_array_add(array1, json_object_new_int(3));  

json_object_object_add(obj1, "array1", array1);

array2 = json_object_new_array();
json_object_array_add(array2, json_object_new_int(4));
json_object_array_add(array2, json_object_new_int(5));
json_object_array_add(array2, json_object_new_int(6));  

json_object_object_add(obj1, "array2", array2);

json_object_object_add(obj1, "array3", array1+array2);

但是我得到了以下错误:

error: invalid operands to binary + (have ‘struct json_object *’ and ‘struct json_object *’) json_object_object_add(obj1, "array3", array1+array2);

这不可能吗?我需要这样的输出:

{
   "array1:[1,2,3],
   "array2":[4,5,6],
   "array3":[1,2,3,4,5,6]
}

或者是否可以将普通的 C 整数数组添加到 Json,像这样

int32_t smp[100]={0};

smp[0] = 1;
smp[1] = 2;
smp[2] = 3;
smp[3] = 4;
smp[4] = 5;
smp[5] = 6;

json_object_object_add(obj1, "array3", smp);

据我所知,json-c 中没有 "built-in" 函数连接两个数组,但您可以轻松创建一个:

struct json_object * json_object_array_concat (struct json_object *array1,
                                               struct json_object *array2) {
    struct json_object *array3 = json_object_new_array();
    if (!array3) {
        return NULL;
    }
    int i,
        size1 = json_object_array_length(array1),
        size2 = json_object_array_length(array2);
    for (i = 0; i < size1; ++i) {
        json_object_array_add(array3, json_object_array_get_idx(array1, i));
    }
    for (i = 0; i < size2; ++i) {
        json_object_array_add(array3, json_object_array_get_idx(array2, i));
    }
    return array3;
}

然后使用它:

array3 = json_object_array_concat(array1, array2);

如果您只想将 array2 附加到 array1:

struct json_object * json_object_array_append (struct json_object *array1,
                                               struct json_object *array2) {
    int i,
        size2 = json_object_array_length(array2);
    for (i = 0; i < size2; ++i) {
        json_object_array_add(array1, json_object_array_get_idx(array2, i));
    }
    return array1;
}

请记住,以上答案并未解决 json-c 中的引用计数问题。他们将对象添加到目标数组,但不让它拥有它们。它们可能会导致段错误等

文档:"The reference count will not be incremented."

为了确保所有权由两个数组持有,您需要这样的东西:

void json_object_array_append(json_object *dest, json_object *src) {
    int i;
    int src_size = json_object_array_length(src);
    for (i = 0; i < src_size; ++i) {
        json_object *src_item = json_object_array_get_idx(src, i);
        json_object_get(src_item); // increment reference count
        json_object_array_add(dest, src_item); // add to dest array
    }
}

// optional: if you are disposing of the src array, you can then do this:
json_object_put(src);
// after calling the append function.