CBOR to cJSON convert
Cloud you add example CBOR to JSON convert?
Fill the blank recursively. So making examples are heavily dependent of what APIs you use, as well as, your translation ruleset you want to apply between certain data types i.e such as maps for instance JSONObject only knows key-strings representation and they must be unique, CBOR map doesn't (the "right" translation would be an array of value-pairs i.e arrays [ [ key, val ], ... ]); same case happens for bytestring, datetime and so on. The following is from JSON to CBOR,chowever, you have here the conceptual approach and principle of a recursive descent process; the only thing that matters to understand; the rest is up to you. Software are not made from examples but understandings.
//!# using libparson
cbor_item_t * jsonarray_to_cborarray(const JSON_Value * val)
{
cbor_item_t * arr = NULL;
...
return arr;
}
cbor_item_t * jsonvalue_to_cboritem(const JSON_Value * val)
{
cbor_item_t * any = NULL;
JSON_Value_Type type = JSONError;
const char * v_string;
double v_double;
bool v_bool;
if (val != NULL) {
type = json_value_get_type(val);
switch (type)
{
case JSONString:
{
v_string = json_value_get_string(val);
if (v_string != NULL) {
any = cbor_build_string(v_string);
}
}
break;
case JSONNumber:
{
v_double = json_value_get_number(val);
/* build integers or floats representation */
// else
any = cbor_build_float8(v_double);
}
break;
case JSONBoolean:
{
v_bool = json_value_get_boolean(val) != 0 ? true : false;
any = cbor_build_bool(v_bool);
}
break;
case JSONObject:
{
any = jsonobject_to_cbormap(val);
}
break;
case JSONArray:
{
any = jsonarray_to_cborarray(val);
}
break;
case JSONNull:
{
any = cbor_new_null();
}
break;
default:
{
any = NULL;
}
break;
}
}
return any;
}
cbor_item_t * jsonobject_to_cbormap(const JSON_Value * val)
{
cbor_item_t * map = NULL;
const char * k;
JSON_Value * v;
cbor_item_t * kk;
cbor_item_t * vv;
size_t n, i = 0;
if (val != NULL) {
if (json_value_get_type(val) == JSONObject) {
n = json_object_get_count(json_value_get_object(val));
map = cbor_new_definite_map(n);
if (map != NULL) {
for (; i < n ; i++) {
k = json_object_get_name(json_value_get_object(val), i);
if (k != NULL) {
kk = cbor_build_string(k);
if (kk != NULL) {
v = json_object_get_value(json_value_get_object(val), k);
if (v != NULL) {
vv = jsonvalue_to_cboritem(v);
if (vv != NULL) {
cbor_map_add(map, (struct cbor_pair) {
.key = cbor_move(kk)
, .value = cbor_move(vv)
});
} else {
cbor_decref(&kk);
cbor_decref(&map);
map = NULL;
break;
}
} else {
cbor_decref(&kk);
cbor_decref(&map);
map = NULL;
break;
}
}
}
}
}
}
}
return map;
}