1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

json2: encode map (#16928)

This commit is contained in:
Hitalo Souza
2023-03-24 08:45:26 -03:00
committed by GitHub
parent bfb0932588
commit 979066856b
5 changed files with 232 additions and 105 deletions

View File

@@ -61,8 +61,8 @@ mut:
reg_date time.Time
}
// // User struct needs to be `pub mut` for now in order to access and manipulate values
struct User {
// User struct needs to be `pub mut` for now in order to access and manipulate values
pub struct User {
pub mut:
age int
nums []int
@@ -264,3 +264,56 @@ fn test_encode_alias_field() {
})
assert s == '{"sub":{"a":1}}'
}
pub struct City {
mut:
name string
}
pub struct Country {
mut:
cities []City
name string
}
struct Data {
mut:
countries []Country
users map[string]User
}
fn test_nested_type() {
data_expected := '{"countries":[{"cities":[{"name":"London"},{"name":"Manchester"}],"name":"UK"},{"cities":[{"name":"Donlon"},{"name":"Termanches"}],"name":"KU"}],"users":{"Foo":{"age":10,"nums":[1,2,3],"lastName":"Johnson","IsRegistered":true,"type":0,"pet_animals":"little foo"},"Boo":{"age":20,"nums":[5,3,1],"lastName":"Smith","IsRegistered":false,"type":4,"pet_animals":"little boo"}}}'
data := Data{
countries: [
Country{
name: 'UK'
cities: [City{'London'}, City{'Manchester'}]
},
Country{
name: 'KU'
cities: [City{'Donlon'}, City{'Termanches'}]
},
]
users: {
'Foo': User{
age: 10
nums: [1, 2, 3]
last_name: 'Johnson'
is_registered: true
typ: 0
pets: 'little foo'
}
'Boo': User{
age: 20
nums: [5, 3, 1]
last_name: 'Smith'
is_registered: false
typ: 4
pets: 'little boo'
}
}
}
out := json.encode(data)
assert out == data_expected
}

View File

@@ -112,6 +112,31 @@ pub mut:
pets string [json: 'pet_animals'; raw]
}
fn test_parse_user() {
s := '{"age": 10, "nums": [1,2,3], "type": 1, "lastName": "Johnson", "IsRegistered": true, "pet_animals": {"name": "Bob", "animal": "Dog"}}'
u2 := json.decode[User2](s)!
u := json.decode[User](s)!
assert u.age == 10
assert u.last_name == 'Johnson'
assert u.is_registered == true
assert u.nums.len == 3
assert u.nums[0] == 1
assert u.nums[1] == 2
assert u.nums[2] == 3
assert u.typ == 1
assert u.pets == '{"name":"Bob","animal":"Dog"}'
}
//! BUGFIX - .from_json(res)
fn test_encode_decode_time() {
user := User2{
age: 25
reg_date: time.new_time(year: 2020, month: 12, day: 22, hour: 7, minute: 23)
}
s := json.encode(user)
assert s.contains('"reg_date":1608621780')
user2 := json.decode[User2](s)!
assert user2.reg_date.str() == '2020-12-22 07:23:00'
struct City {
name string
}