9

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

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);

但我收到以下错误:

错误:二进制 + 的无效操作数(有 'struct json_object *' 和 '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);
4

2 回答 2

2

据我所知,没有“内置”函数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);

如果您只想附加array2array1

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;
}
于 2016-05-03T09:07:20.420 回答
1

请记住,上述答案并未解决 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.
于 2017-06-08T05:00:44.117 回答