mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
json2: fix decode result with option fields (#17561)
This commit is contained in:
parent
b19052949f
commit
785546f277
13
vlib/x/json2/encode_option_test.v
Normal file
13
vlib/x/json2/encode_option_test.v
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import x.json2
|
||||||
|
|
||||||
|
struct JoseHeader {
|
||||||
|
pub mut:
|
||||||
|
cty ?string
|
||||||
|
alg string
|
||||||
|
typ string = 'JWT'
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test_main() {
|
||||||
|
res := json2.encode(JoseHeader{ alg: 'HS256' })
|
||||||
|
assert res == '{"alg":"HS256","typ":"JWT"}'
|
||||||
|
}
|
@ -154,6 +154,7 @@ fn (e &Encoder) encode_struct[U](val U, level int, mut wr io.Writer) ! {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
$for field in U.fields {
|
$for field in U.fields {
|
||||||
|
mut ignore_field := false
|
||||||
value := val.$(field.name)
|
value := val.$(field.name)
|
||||||
mut json_name := ''
|
mut json_name := ''
|
||||||
for attr in field.attrs {
|
for attr in field.attrs {
|
||||||
@ -219,6 +220,8 @@ fn (e &Encoder) encode_struct[U](val U, level int, mut wr io.Writer) ! {
|
|||||||
} $else {
|
} $else {
|
||||||
return error('type ${typeof(val).name} cannot be array encoded')
|
return error('type ${typeof(val).name} cannot be array encoded')
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
ignore_field = true
|
||||||
}
|
}
|
||||||
} $else {
|
} $else {
|
||||||
is_none := val.$(field.name).str() == 'unknown sum type value'
|
is_none := val.$(field.name).str() == 'unknown sum type value'
|
||||||
@ -345,10 +348,12 @@ fn (e &Encoder) encode_struct[U](val U, level int, mut wr io.Writer) ! {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if i < fields_len - 1 {
|
if i < fields_len - 1 && !ignore_field {
|
||||||
wr.write(json2.comma_bytes)!
|
wr.write(json2.comma_bytes)!
|
||||||
}
|
}
|
||||||
i++
|
if !ignore_field {
|
||||||
|
i++
|
||||||
|
}
|
||||||
}
|
}
|
||||||
e.encode_newline(level - 1, mut wr)!
|
e.encode_newline(level - 1, mut wr)!
|
||||||
wr.write([u8(`}`)])!
|
wr.write([u8(`}`)])!
|
||||||
|
Loading…
Reference in New Issue
Block a user