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

json: fix json with option struct (#17942)

This commit is contained in:
Felipe Pena 2023-04-13 03:17:40 -03:00 committed by GitHub
parent 3d99f1f2c2
commit 524f7c3ead
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 4 deletions

View File

@ -0,0 +1,23 @@
import json
pub struct SomeStruct {
pub mut:
test ?string
}
pub struct MyStruct {
pub mut:
result ?SomeStruct
id string
}
fn test_main() {
a := MyStruct{
id: 'some id'
result: SomeStruct{}
}
encoded_string := json.encode(a)
assert encoded_string == '{"result":{},"id":"some id"}'
test := json.decode(MyStruct, encoded_string)!
assert test == a
}

View File

@ -673,15 +673,15 @@ fn (mut g Gen) gen_struct_enc_dec(utyp ast.Type, type_info ast.TypeInfo, styp st
is_option := field.typ.has_flag(.option) is_option := field.typ.has_flag(.option)
indent := if is_option { '\t\t' } else { '\t' } indent := if is_option { '\t\t' } else { '\t' }
if is_option { if is_option {
enc.writeln('\tif (val${op}${c_name(field.name)}.state != 2) {') enc.writeln('\tif (${prefix_enc}${op}${c_name(field.name)}.state != 2) {')
} }
if is_omit_empty { if is_omit_empty {
if field.typ.has_flag(.option) { if field.typ.has_flag(.option) {
enc.writeln('${indent}if (val${op}${c_name(field.name)}.state != 2)') enc.writeln('${indent}if (${prefix_enc}${op}${c_name(field.name)}.state != 2)')
} else if field.typ == ast.string_type { } else if field.typ == ast.string_type {
enc.writeln('${indent}if (val${op}${c_name(field.name)}.len != 0)') enc.writeln('${indent}if (${prefix_enc}${op}${c_name(field.name)}.len != 0)')
} else { } else {
enc.writeln('${indent}if (val${op}${c_name(field.name)} != ${g.type_default(field.typ)})') enc.writeln('${indent}if (${prefix_enc}${op}${c_name(field.name)} != ${g.type_default(field.typ)})')
} }
} }
if !is_js_prim(field_type) { if !is_js_prim(field_type) {