x.json2: support @[skip] as well (#22077)

This commit is contained in:
Carlos Esquerdo Bernat 2024-08-19 14:49:31 +02:00 committed by GitHub
parent c8dc145468
commit 4188deb96d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 57 additions and 0 deletions

View File

@ -165,6 +165,9 @@ fn decode_struct[T](_ T, res map[string]Any) !T {
mut json_name := field.name
for attr in field.attrs {
if attr.contains('skip') {
skip_field = true
}
if attr.contains('json: ') {
json_name = attr.replace('json: ', '')
if json_name == '-' {

View File

@ -200,6 +200,9 @@ fn (e &Encoder) encode_struct[U](val U, level int, mut buf []u8) ! {
$for field in U.fields {
mut @continue := false
for attr in field.attrs {
if attr.contains('skip') {
@continue = true
}
if attr.contains('json: ') {
if attr.replace('json: ', '') == '-' {
@continue = true
@ -227,6 +230,9 @@ fn (e &Encoder) encode_struct[U](val U, level int, mut buf []u8) ! {
mut json_name := ''
for attr in field.attrs {
if attr.contains('skip') {
ignore_field = true
}
if attr.contains('json: ') {
json_name = attr.replace('json: ', '')
if json_name == '-' {

View File

@ -73,6 +73,22 @@ mut:
val map[string]string @[json: '-']
}
struct StructTypeSkippedFields5[T] {
mut:
val T @[skip]
val1 T @[skip]
val2 T @[skip]
val3 T @[skip]
}
struct StructTypeSkippedFields6[T] {
mut:
val T
val1 T @[skip]
val2 T
val3 T @[skip]
}
fn test_types() {
assert json.decode[StructType[string]]('{"val": ""}')!.val == ''
assert json.decode[StructType[string]]('{"val": "0"}')!.val == '0'
@ -188,4 +204,22 @@ fn test_skipped_fields() {
} else {
assert false
}
if x := json.decode[StructTypeSkippedFields5[int]]('{"val":10,"val1":10,"val2":10,"val3":10}') {
assert x.val == 0
assert x.val1 == 0
assert x.val2 == 0
assert x.val3 == 0
} else {
assert false
}
if x := json.decode[StructTypeSkippedFields6[int]]('{"val":10,"val1":10,"val2":10,"val3":10}') {
assert x.val == 10
assert x.val1 == 0
assert x.val2 == 10
assert x.val3 == 0
} else {
assert false
}
}

View File

@ -73,6 +73,14 @@ mut:
val3 time.Time @[json: '-']
}
struct StructTypeSkippedFields9 {
mut:
val string
val1 i64 @[skip]
val2 f64
val3 time.Time @[skip]
}
fn test_encode_struct_skipped_fields() {
assert json.encode(StructTypeSkippedFields[string]{
val: 'string_val'
@ -131,4 +139,10 @@ fn test_encode_struct_skipped_fields() {
val1: 1
val2: 1.0
}) == '{"val":"string_val","val2":1.0}'
assert json.encode(StructTypeSkippedFields9{
val: 'string_val'
val1: 1
val2: 1.0
}) == '{"val":"string_val","val2":1.0}'
}