Skip to content

Commit 54fec7b

Browse files
authored
x.json2.decoder2: fix option decode (fix #24861) (#24881)
1 parent 34c6787 commit 54fec7b

2 files changed

Lines changed: 25 additions & 2 deletions

File tree

vlib/x/json2/decoder2/decode.v

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -797,7 +797,9 @@ fn (mut decoder Decoder) decode_value[T](mut val T) ! {
797797
}
798798
} else {
799799
$if field.typ is $option {
800-
mut unwrapped_val := create_value_from_optional(val.$(field.name))
800+
mut unwrapped_val := create_value_from_optional(val.$(field.name)) or {
801+
return
802+
}
801803
decoder.decode_value(mut unwrapped_val)!
802804
val.$(field.name) = unwrapped_val
803805
} $else {
@@ -961,7 +963,7 @@ fn get_value_kind(value u8) ValueKind {
961963
return .unknown
962964
}
963965

964-
fn create_value_from_optional[T](val ?T) T {
966+
fn create_value_from_optional[T](val ?T) ?T {
965967
return T{}
966968
}
967969

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import x.json2.decoder2
2+
3+
struct F1 {
4+
f ?struct {
5+
a int
6+
}
7+
}
8+
9+
fn test_main() {
10+
j1 := decoder2.decode[F1]('{"f":{"a":1}}')!
11+
assert '${j1}' == 'F1{
12+
f: Option(struct {
13+
a: 1
14+
})
15+
}'
16+
17+
j2 := decoder2.decode[F1]('{}')!
18+
assert '${j2}' == 'F1{
19+
f: Option(none)
20+
}'
21+
}

0 commit comments

Comments
 (0)