1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

json: fix raw decode to option string of complex data (#18902)

This commit is contained in:
Felipe Pena 2023-07-19 20:33:39 -03:00 committed by GitHub
parent a49b8f28b1
commit 511274a8d4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 63 additions and 1 deletions

View File

@ -0,0 +1,62 @@
import json
pub struct Dto {
pub:
key string [raw]
key2 string [raw]
data ?string [raw]
optional ?string [raw]
}
fn test_main() {
raw_json := '{
"key": [1, 2, "test"],
"key2": { "test": 1 },
"data": { "test": 1 },
"optional": "test"
}'
dto := json.decode(Dto, raw_json)!
println(dto)
assert dto.data? == '{"test":1}'
}
fn test_none() {
raw_json := '{
"key": [1, 2, "test"],
"optional": "test"
}'
dto := json.decode(Dto, raw_json)!
println(dto)
assert dto.data == none
assert dto.optional? == '"test"'
}
fn test_null() {
raw_json := '{
"key": [1, 2, "test"],
"key2": null,
"data": null,
"optional": "test"
}'
dto := json.decode(Dto, raw_json)!
println(dto)
assert dto.key2 == 'null'
assert dto.data? == 'null'
}
fn test_not_set() {
raw_json := '{
}'
dto := json.decode(Dto, raw_json)!
println(dto)
assert dto.data == none
assert dto.optional == none
}

View File

@ -629,7 +629,7 @@ fn (mut g Gen) gen_struct_enc_dec(utyp ast.Type, type_info ast.TypeInfo, styp st
if field.typ.has_flag(.option) { if field.typ.has_flag(.option) {
g.gen_json_for_type(field.typ) g.gen_json_for_type(field.typ)
base_typ := g.base_type(field.typ) base_typ := g.base_type(field.typ)
dec.writeln('\tif (!cJSON_IsString(js_get(root, "${name}")))') dec.writeln('\tif (js_get(root, "${name}") == NULL)')
dec.writeln('\t\t_option_none(&(${base_typ}[]) { {0} }, &${prefix}${op}${c_name(field.name)}, sizeof(${base_typ}));') dec.writeln('\t\t_option_none(&(${base_typ}[]) { {0} }, &${prefix}${op}${c_name(field.name)}, sizeof(${base_typ}));')
dec.writeln('\telse') dec.writeln('\telse')
dec.writeln('\t\t_option_ok(&(${base_typ}[]) { tos5(cJSON_PrintUnformatted(js_get(root, "${name}"))) }, &${prefix}${op}${c_name(field.name)}, sizeof(${base_typ}));') dec.writeln('\t\t_option_ok(&(${base_typ}[]) { tos5(cJSON_PrintUnformatted(js_get(root, "${name}"))) }, &${prefix}${op}${c_name(field.name)}, sizeof(${base_typ}));')