【问题标题】:Accessing a struct variable with an array of structs variables golang使用结构变量数组访问结构变量golang
【发布时间】:2018-09-01 03:07:39
【问题描述】:
func GetprofilesApi(c *gin.Context) {
var p Profile
profiles, err, count := p.GetProfiles()
if err != nil {
    log.Fatalln(err)
}

c.JSON(http.StatusOK, gin.H{
    "Number of Results": count,

    "profiles": profiles,
}) }

//Getprofiles() function
func (p *Profile) GetProfiles() (profiles []Profile, err error, count int) {
profiles = make([]Profile, 0)
rows, err := db.Query("SELECT id, firstname, lastname, email, username, phone, function  FROM profile")
defer rows.Close()

if err != nil {
    return
}
//counting rows

for rows.Next() {
    var profile Profile
    rows.Scan(&profile.ID, &profile.FirstName, &profile.LastName, &profile.Email, &profile.Username, &profile.Phone, &profile.Function)
    profiles = append(profiles, profile)
    count = count + 1
}
if err = rows.Err(); err != nil {
    return
}
return}

我在获取每个对象的用户名配置文件时遇到了问题

您可能会看到 Getprofiles() 返回所有字段,因此在 GetprofilesApi() 中我只想返回 json 结果中的用户名字段

感谢您的任何建议!

配置文件结构是:

type Profile struct {
ID        int    `json:"id"`
FirstName string `json:"firstname"`
LastName  string `json:"lastname"`
Username  string `json:"username"`
Email     string `json:"email"`
Phone     string `json:"phone"`
Function  string `json:"function"`}

json result

【问题讨论】:

  • 我不明白这个问题。请粘贴您要返回的示例 JSON 文档。
  • @Peter 感谢您的合作,这里是我的结果的截图(通常它会给我所有的配置文件字段,但我只想拥有每个对象的用户名字段
  • 这个问题不清楚。请提供有关您的期望、您尝试过的内容以及您正在尝试做的事情的更多信息。
  • @JakeHeidt 我编辑添加了附加信息,希望问题能被理解
  • @dev_medo 您可以仅从配置文件中要公开的那些字段创建map[string]interface{},并编组该映射而不是结构。

标签: arrays json go struct interface


【解决方案1】:

json:"-" 标记不包括用于 JSON 封送和取消封送的字段。定义一个与 Person 具有相同字段的新类型,然后对该类型的切片进行编码(为简洁起见,省略一些字段):

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

type Profile struct {
    ID       int    `json:"id"`
    Username string `json:"username"`
    Email    string `json:"email"`
}

type ProfileSummary struct {
    ID       int    `json:"-"`
    Username string `json:"username"`
    Email    string `json:"-"`
}

func main() {
    var profiles []Profile
    profiles = append(profiles, Profile{Username: "john", Email: "john.doe@example.com"})
    profiles = append(profiles, Profile{Username: "jane", Email: "jane.doe@example.com"})

    summaries := make([]ProfileSummary, len(profiles))
    for i, p := range profiles {
            summaries[i] = ProfileSummary(p)
    }

    b, err := json.MarshalIndent(summaries, "", "  ")
    if err != nil {
            log.Fatal(err)
    }

    fmt.Println(string(b))
}

在操场上试试看:https://play.golang.org/p/y3gP5IZDWzl

【讨论】:

    猜你喜欢
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 2016-07-11
    • 1970-01-01
    • 2023-03-26
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多