From 656009dc620044f4c07928ad068ec1417f55576e Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Tue, 2 Apr 2024 07:54:36 +0530 Subject: [PATCH] json: allow `i32` decoding and encoding (#21162) --- vlib/json/json_i32_test.v | 16 ++++++++++++++++ vlib/v/gen/c/json.v | 14 ++++++++++---- 2 files changed, 26 insertions(+), 4 deletions(-) create mode 100644 vlib/json/json_i32_test.v diff --git a/vlib/json/json_i32_test.v b/vlib/json/json_i32_test.v new file mode 100644 index 00000000000000..b23df17e2e7c46 --- /dev/null +++ b/vlib/json/json_i32_test.v @@ -0,0 +1,16 @@ +import json + +pub struct StructB { + kind string + value i32 +} + +fn test_json_i32() { + struct_b := json.decode(StructB, '{"kind": "Int32", "value": 100}')! + assert struct_b == StructB{ + kind: 'Int32' + value: 100 + } + + assert json.encode(struct_b) == '{"kind":"Int32","value":100}' +} diff --git a/vlib/v/gen/c/json.v b/vlib/v/gen/c/json.v index 9c0b94a89ca76d..cf0e22d4fea563 100644 --- a/vlib/v/gen/c/json.v +++ b/vlib/v/gen/c/json.v @@ -902,20 +902,26 @@ fn gen_js_get_opt(dec_name string, field_type string, styp string, tmp string, n } fn js_enc_name(typ string) string { - suffix := typ.replace('*', '_ptr') + mut suffix := typ.replace('*', '_ptr') + if typ == 'i32' { + suffix = typ.replace('i32', 'int') + } name := 'json__encode_${suffix}' return util.no_dots(name) } fn js_dec_name(typ string) string { - suffix := typ.replace('*', '_ptr') + mut suffix := typ.replace('*', '_ptr') + if typ == 'i32' { + suffix = typ.replace('i32', 'int') + } name := 'json__decode_${suffix}' return util.no_dots(name) } fn is_js_prim(typ string) bool { - return typ in ['int', 'rune', 'string', 'bool', 'f32', 'f64', 'i8', 'i16', 'i64', 'u8', 'u16', - 'u32', 'u64', 'byte'] + return typ in ['int', 'rune', 'string', 'bool', 'f32', 'f64', 'i8', 'i16', 'i32', 'i64', 'u8', + 'u16', 'u32', 'u64', 'byte'] } fn (mut g Gen) decode_array(utyp ast.Type, value_type ast.Type, fixed_array_size int, ret_styp string) string {