From 2ad2d68d7c07d331db858295c743b01215d63697 Mon Sep 17 00:00:00 2001 From: yuyi Date: Fri, 8 Jan 2021 03:21:22 +0800 Subject: [PATCH] json: fix decoding of null map/array (#7936) --- vlib/json/json_test.v | 13 +++++++++++++ vlib/v/gen/json.v | 4 ++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/vlib/json/json_test.v b/vlib/json/json_test.v index 24e10e899f..c1e875b3b0 100644 --- a/vlib/json/json_test.v +++ b/vlib/json/json_test.v @@ -366,3 +366,16 @@ fn test_list_no_items() { assert list.id == 1 assert list.items == [] } + +struct Info { + id int + items []string + maps map[string]string +} + +fn test_decode_null_object() { + info := json.decode(Info, '{"id": 22, "items": null, "maps": null}') or { panic(err) } + assert info.id == 22 + assert '$info.items' == '[]' + assert '$info.maps' == '{}' +} diff --git a/vlib/v/gen/json.v b/vlib/v/gen/json.v index 733ab85854..74343ae8b7 100644 --- a/vlib/v/gen/json.v +++ b/vlib/v/gen/json.v @@ -222,7 +222,7 @@ fn (mut g Gen) decode_array(value_type table.Type) string { ' } return ' - if(root && !cJSON_IsArray(root)) { + if(root && !cJSON_IsArray(root) && !cJSON_IsNull(root)) { Option err = v_error( string_add(_SLIT("Json element is not an array: "), tos2(cJSON_PrintUnformatted(root))) ); return *(Option_array_$styp *)&err; } @@ -267,7 +267,7 @@ fn (mut g Gen) decode_map(key_type table.Type, value_type table.Type) string { ' } return ' - if(!cJSON_IsObject(root)) { + if(!cJSON_IsObject(root) && !cJSON_IsNull(root)) { Option err = v_error( string_add(_SLIT("Json element is not an object: "), tos2(cJSON_PrintUnformatted(root))) ); return *(Option_map_${styp}_$styp_v *)&err; }