x.json2.decoder2: fix option decode (fix #24861) (#24881)

This commit is contained in:
Felipe Pena 2025-07-13 04:26:45 -03:00 committed by GitHub
parent 34c67878b9
commit 54fec7b772
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 25 additions and 2 deletions

View file

@ -797,7 +797,9 @@ fn (mut decoder Decoder) decode_value[T](mut val T) ! {
} }
} else { } else {
$if field.typ is $option { $if field.typ is $option {
mut unwrapped_val := create_value_from_optional(val.$(field.name)) mut unwrapped_val := create_value_from_optional(val.$(field.name)) or {
return
}
decoder.decode_value(mut unwrapped_val)! decoder.decode_value(mut unwrapped_val)!
val.$(field.name) = unwrapped_val val.$(field.name) = unwrapped_val
} $else { } $else {
@ -961,7 +963,7 @@ fn get_value_kind(value u8) ValueKind {
return .unknown return .unknown
} }
fn create_value_from_optional[T](val ?T) T { fn create_value_from_optional[T](val ?T) ?T {
return T{} return T{}
} }

View file

@ -0,0 +1,21 @@
import x.json2.decoder2
struct F1 {
f ?struct {
a int
}
}
fn test_main() {
j1 := decoder2.decode[F1]('{"f":{"a":1}}')!
assert '${j1}' == 'F1{
f: Option(struct {
a: 1
})
}'
j2 := decoder2.decode[F1]('{}')!
assert '${j2}' == 'F1{
f: Option(none)
}'
}