douye6812 2019-03-16 10:33
浏览 4
已采纳

如何将结构片段编组为有效的JSON

I'm writing a Golang api and client but can't get valid json from a slice of structs in the api. The result I get in my client looks like this.

[{0 Mark 1234 false} {0 John 3456 false}]

I need this json to look like

[{"id":0, "name":Mark, "pin":1234, "active":false} {"id":0, "name":John, "pin":3456, "active":false}]

I can't find examples showing me how to code this properly and this is not a duplicate of anything I can find despite a warning that it is. While my client successfully parses the JSON back to a struct, I also need it to return JSON to an IOS client which is requesting it. The flow is API -> API -> iOS client. I don't know how to produce JSON from the struct for the iOS client.

Here is my api code.

// Employee model
type Employee struct {
    EmployeeID int64  `json:"id"`
    Name       string `json:"name"`
    Pin        int    `json:"pin"`
    Active     bool   `json:"active"`
}

func getEmployees(db *sql.DB, venueID int64) ([]Employee, error) {

    var employee Employee

    var employees []Employee

    query, err := db.Query("SELECT id, name, pin FROM employees WHERE active=1 AND venue_id=? ORDER BY name", venueID)
    if err != nil {
        return employees, err
    }

    defer query.Close()

    for query.Next() {
        err = query.Scan(&employee.EmployeeID, &employee.Name, &employee.Pin)
        if err != nil {
            return employees, err
        }
        employees = append(employees, employee)
    }

    return employees, err
}



func (rs *appResource) listEmployees(w http.ResponseWriter, r *http.Request) {

    var venue Venue

    token := getToken(r)

    fmt.Println(token)

    venue, err := getVenue(rs.db, token)

    if err != nil {
        log.Fatal(err)
        return
    }

    venueID := venue.VenueID

    if !(venueID > 0) {
        http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
        return
    }

    employees, err := getEmployees(rs.db, venueID)

    if err != nil {
        log.Fatal(err)
        return
    }

    fmt.Println(employees[0].EmployeeID)

    employeesJSON, err := json.Marshal(employees)
    if err != nil {
        log.Fatal(err)
        return
    }

    w.Write([]byte(employeesJSON))

}

Here is my client code:

func (rs *appResource) getEmployees(w http.ResponseWriter, r *http.Request) {

    path := rs.url + "/employees"

    fmt.Println(path)

    res, err := rs.client.Get(path)

    if err != nil {
        log.Println("error in get")
        log.Fatal(err)
        http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
        return
    }

    defer res.Body.Close()

    if res.StatusCode == 500 {
        fmt.Printf("res.StatusCode: %d
", res.StatusCode)
        http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
        return

    }

    if res.StatusCode == 404 {
        fmt.Printf("res.StatusCode: %d
", res.StatusCode)
        http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
        return
    }

    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        log.Fatal(err)
        http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
        return
    }

// here I want to return actual JSON to an iOS client    

    w.WriteHeader(http.StatusOK)
    w.Write([]byte("{ok}"))
}
  • 写回答

3条回答 默认 最新

  • dphs48626 2019-03-16 11:24
    关注

    What your code is currently printing is the content of a struct, not JSON. When you print the contents of a struct, by default, you will print just the values within that struct. That means that fmt.Println(employees.EmployeeList) will produce something like:

    [{0 Mark 1234 false} {0 John 3456 false}]
    

    If you want to also print field values, you'll need to add a format 'verb' %+v which will print field names. fmt.Printf("%+v ", employees.EmployeeList) should print something like:

    [{id:0 name:Mark pin:1234 active:false} {id:0 name:John pin:3456 active:false}]
    

    I think what you actually want to look at doing is marshalling your data back into a JSON string again in order to write that content back out for the client.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 java大作业爬取网页
  • ¥15 怎么获取欧易的btc永续合约和交割合约的5m级的历史数据用来回测套利策略?
  • ¥15 有没有办法利用libusb读取usb设备数据
  • ¥15 为什么openeluer里面按不了python3呢?
  • ¥15 关于#matlab#的问题:训练序列与输入层维度不一样
  • ¥15 关于Ubuntu20.04.3LTS遇到的问题:在安装完CUDA驱动后,电脑会进入卡死的情况,但可以通过键盘按键进入安全重启,但重启完又会进入该情况!
  • ¥15 关于#嵌入式硬件#的问题:树莓派第一天重装配置python和opencv后第二天打开就成这样,瞎捣鼓搞出来文件夹还是没把原来的界面调回来
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥15 C++数组中找第二小的数字程序纠错