Skip to content

Commit 656009d

Browse files
authored
json: allow i32 decoding and encoding (#21162)
1 parent c086bee commit 656009d

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

vlib/json/json_i32_test.v

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import json
2+
3+
pub struct StructB {
4+
kind string
5+
value i32
6+
}
7+
8+
fn test_json_i32() {
9+
struct_b := json.decode(StructB, '{"kind": "Int32", "value": 100}')!
10+
assert struct_b == StructB{
11+
kind: 'Int32'
12+
value: 100
13+
}
14+
15+
assert json.encode(struct_b) == '{"kind":"Int32","value":100}'
16+
}

vlib/v/gen/c/json.v

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -902,20 +902,26 @@ fn gen_js_get_opt(dec_name string, field_type string, styp string, tmp string, n
902902
}
903903

904904
fn js_enc_name(typ string) string {
905-
suffix := typ.replace('*', '_ptr')
905+
mut suffix := typ.replace('*', '_ptr')
906+
if typ == 'i32' {
907+
suffix = typ.replace('i32', 'int')
908+
}
906909
name := 'json__encode_${suffix}'
907910
return util.no_dots(name)
908911
}
909912

910913
fn js_dec_name(typ string) string {
911-
suffix := typ.replace('*', '_ptr')
914+
mut suffix := typ.replace('*', '_ptr')
915+
if typ == 'i32' {
916+
suffix = typ.replace('i32', 'int')
917+
}
912918
name := 'json__decode_${suffix}'
913919
return util.no_dots(name)
914920
}
915921

916922
fn is_js_prim(typ string) bool {
917-
return typ in ['int', 'rune', 'string', 'bool', 'f32', 'f64', 'i8', 'i16', 'i64', 'u8', 'u16',
918-
'u32', 'u64', 'byte']
923+
return typ in ['int', 'rune', 'string', 'bool', 'f32', 'f64', 'i8', 'i16', 'i32', 'i64', 'u8',
924+
'u16', 'u32', 'u64', 'byte']
919925
}
920926

921927
fn (mut g Gen) decode_array(utyp ast.Type, value_type ast.Type, fixed_array_size int, ret_styp string) string {

0 commit comments

Comments
 (0)