json: wrap up: encode_array()

pull/4732/head
Alexander Medvednikov 2020-05-05 14:54:12 +02:00
parent b3d7b0205a
commit 148661ead6
2 changed files with 15 additions and 3 deletions

View File

@ -49,11 +49,11 @@ fn test_parse_user() {
assert u.typ == 1
}
/*
fn test_encode_user(){
usr := User{ age: 10, nums: [1,2,3], last_name: 'Johnson', is_registered: true, typ: 0}
expected := '{"age":10,"nums":[1,2,3],"lastName":"Johnson","IsRegistered":true,"type":0}'
out := json.encode(usr)
println(out)
assert out == expected
}
@ -70,4 +70,4 @@ fn test_raw_json_field() {
assert color.point == '{"Y":123}'
assert color.space == 'YCbCr'
}
*/

View File

@ -61,6 +61,7 @@ cJSON* ${enc_fn_name}($styp val) {
value_type := g.table.value_type(typ)
g.gen_json_for_type(value_type)
dec.writeln(g.decode_array(value_type))
enc.writeln(g.encode_array(value_type))
// enc += g.encode_array(t)
} else {
// Structs. Range through fields
@ -76,7 +77,7 @@ cJSON* ${enc_fn_name}($styp val) {
field_type := g.typ(field.typ)
enc_name := js_enc_name(field_type)
if field.attr == 'raw' {
dec.writeln(' res->$field.name = tos2(cJSON_PrintUnformatted(' + 'js_get(root, "$name")));')
dec.writeln(' res . $field.name = tos2(cJSON_PrintUnformatted(' + 'js_get(root, "$name")));')
} else {
// Now generate decoders for all field types in this struct
// need to do it here so that these functions are generated first
@ -136,3 +137,14 @@ $s
}
'
}
fn (mut g Gen) encode_array(value_type table.Type) string {
styp := g.typ(value_type)
fn_name := js_enc_name(styp)
return '
o = cJSON_CreateArray();
for (int i = 0; i < val.len; i++){
cJSON_AddItemToArray(o, $fn_name ( (($styp*)val.data)[i] ));
}
'
}