Skip to content

Commit

Permalink
json2: add support for nested structs (#19579)
Browse files Browse the repository at this point in the history
  • Loading branch information
islonely authored Oct 16, 2023
1 parent 7c4029c commit b8d4764
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
11 changes: 11 additions & 0 deletions vlib/x/json2/decode_struct_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ mut:
val T
}

struct StructTypeSub {
test string
}

struct StructTypeOption[T] {
mut:
val ?T
Expand Down Expand Up @@ -94,4 +98,11 @@ fn test_types() {
// dump(err)
assert true
}

assert json.decode[StructType[StructTypeSub]]('{"val": {"test": "test"}}')!.val.test == 'test'
if x := json.decode[StructType[StructTypeSub]]('{"val": {"invalid_field": "test"}}') {
assert false
} else {
assert true
}
}
9 changes: 7 additions & 2 deletions vlib/x/json2/json2.v
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,13 @@ pub fn fast_raw_decode(src string) !Any {

// decode is a generic function that decodes a JSON string into the target type.
pub fn decode[T](src string) !T {
mut typ := T{}
res := raw_decode(src)!.as_map()
return decode_struct[T](T{}, res)
}

// decode_struct is a generic function that decodes a JSON map into the struct T.
fn decode_struct[T](_ T, res map[string]Any) !T {
mut typ := T{}
$if T is $struct {
$for field in T.fields {
mut json_name := field.name
Expand Down Expand Up @@ -123,8 +128,8 @@ pub fn decode[T](src string) !T {
typ.$(field.name) = res[json_name]!.to_time()!
}
} $else $if field.is_array {
// typ.$(field.name) = res[field.name]!.arr()
} $else $if field.is_struct {
typ.$(field.name) = decode_struct(typ.$(field.name), res[field.name]!.as_map())!
} $else $if field.is_alias {
} $else $if field.is_map {
} $else {
Expand Down

0 comments on commit b8d4764

Please sign in to comment.