如何在结构体中存储对象

huangapple go评论91阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年5月21日 18:39:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/30371353.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定