我是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);
但我得到了以下错误:
错误:binary+的操作数无效(具有"struct json_object*"one_answers"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]
}
或者可以像这个一样,向Json添加一个普通的C整数数组吗
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
中没有"内置"函数来连接两个数组,但您可以轻松创建一个:
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中的引用计数。他们将对象添加到目标阵列中,但不让目标阵列取得对象的所有权。它们可能会导致分段故障等。
文档:"参考计数将不递增。"
为了确保所有权由两个阵列持有,您需要这样的东西:
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.