英文:
How to store object in a struct
问题
我不确定如何创建一个struct
来存储被发送到我的API的JSON对象。
JSON的结构如下:
{
"name" : "Mr Robinson",
"email" : "test@test.com",
"username" : "robbo123",
"properties" : {
"property1" : "a property",
"property2" : "another property"
},
"permissions" : ["perm1", "perm2", "perm3"]
}
properties
可以有任意数量的属性,而permissions
数组可以包含任意数量的值。
我正在使用以下代码解码发送的值:
err := json.NewDecoder(req.Body).Decode(my_struct)
到目前为止,我的struct
看起来像这样:
type User struct {
Name string `json:"name"`
Email string `json:"email"`
Username string `json:"username"`
}
英文:
I'm not sure how to create a struct
to store a JSON object that is being posted to my API.
The JSON looks like this:
{
"name" : "Mr Robinson",
"email" : "test@test.com",
"username" : "robbo123",
"properties" : {
"property1" : "a property",
"property2" : "another property"
},
"permissions" : ["perm1", "perm2", "perm3"]
}
There can be any number of properties
and the permissions
array can contain any number of values.
I am using this to decode the posted values:
err := json.NewDecoder(req.Body).Decode(my_struct)
So far my struct looks like this:
type User struct {
Name string `json:"name"`
Email string `json:"email"`
Username string `json:"username"`
}
答案1
得分: 5
你可以使用map[string]string
来存储属性,使用[]string
切片来存储权限:
type User struct {
Name string `json:"name"`
Email string `json:"email"`
Username string `json:"username"`
Properties map[string]string `json:"properties"`
Permissions []string `json:"permissions"`
}
输出结果(换行显示):
{
Name: "Mr Robinson",
Email: "test@test.com",
Username: "robbo123",
Properties: map[property1:a property property2:another property],
Permissions: [perm1 perm2 perm3]
}
你可以在Go Playground上尝试完整的可运行应用。
英文:
You can use a map[string]string
for the properties and a []string
slice for the permissions:
type User struct {
Name string `json:"name"`
Email string `json:"email"`
Username string `json:"username"`
Properties map[string]string `json:"properties"`
Permissions []string `json:"permissions"`
}
Output (wrapped):
{Name:Mr Robinson Email:test@test.com Username:robbo123
Properties:map[property1:a property property2:another property]
Permissions:[perm1 perm2 perm3]}
Try the complete runnable app on the Go Playground.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论