+ 收藏我们

网站模板

网站模板搜索
404模板 营销型模板 外贸网站模板 单页模板 双语模板 标签大全
电话:18630701785
首页 > 站长学院 > 如何将结构体切片编组为有效的 JSON >

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

时间:2024-04-07 10:22:37

今天我将给大家介绍《如何将结构体切片编组为有效的 JSON》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

问题内容
我正在编写 golang api 和客户端,但无法从 api 中的结构切片获取有效的 json。我在客户端得到的结果如下所示。

[{0 马可福音 1234 错误} {0 约翰福音 3456 错误}]

我需要这个 json 看起来像

[{“id”:0,“name”:马克,“pin”:1234,“active”:false} {“id”:0,“name”:约翰,“pin”:3456,“active”:false }]

我找不到显示如何正确编码的示例,并且这不是我能找到的任何内容的重复,尽管有警告。虽然我的客户端成功地将 json 解析回结构,但我还需要它将 json 返回给请求它的 ios 客户端。流程是api -> api -> iOS 客户端。我不知道如何从 ios 客户端的结构生成 json。

这是我的 api 代码。

// 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))

}
这是我的客户端代码:

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\n", res.StatusCode)
        http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
        return

    }

    if res.StatusCode == 404 {
        fmt.Printf("res.StatusCode: %d\n", 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}"))
}

解决方案

您的代码当前打印的是结构体的内容,而不是 json。当您打印结构体的内容时,默认情况下,您将仅打印该结构体中的值。这意味着 fmt.println(employees.employeelist) 将产生类似以下内容:

[{0 mark 1234 false} {0 john 3456 false}]
如果您还想打印字段值,则需要添加格式“verb”%+v,它将打印字段名称。 fmt.printf("%+v\n",employees.employeelist) 应该打印如下内容:

[{id:0 name:mark pin:1234 active:false} {id:0 name:john pin:3456 active:false}]
我认为您真正想要做的是将数据再次编组回 json 字符串,以便将该内容写回给客户端。

我实际上对您的代码感到惊讶正在运行,因为您有 2 个未使用的变量(err,err at listemployees)。 任何可行的方式,添加一个 fmt.println 这样你就可以在控制台看到结果

type employee struct {
        id     int    `json:"id"`
        name   string `json:"name"`
        pin    int    `json:"pin"`
        active bool   `json:"active"`
    }

    func (rs *appresource) listemployees(w http.responsewriter, r *http.request) {
        employees, _:= getemployees(rs.db)
        employeesjson, _:= json.marshal(employees)
        fmt.ptintln(string(employeesjson))
        w.write(employeesjson)
    }
另一个运行示例:

func main() {
    emp := Employee{
        ID:     1,
        Name:   "Mark",
        Pin:    1234,
        Active: true,
    }
    if jsn, err := json.Marshal(emp); err == nil {
        fmt.Println(string(jsn))
    } else {
        log.Panic(err)
    }

}

type Employee struct {
    ID     int    `json:"id"`
    Name   string `json:"name"`
    Pin    int    `json:"pin"`
    Active bool   `json:"active"`
}
输出:

终于介绍完啦!小伙伴们,这篇关于《如何将结构体切片编组为有效的 JSON》的介绍应该让你收获多多了吧!

有问题可以加入网站技术QQ群一起交流学习

本站会员学习、解决问题QQ群(691961965)

客服微信号:lpf010888

pbootcms教程

织梦教程

站长学院

SEO

wordpress

竞价教程

信息流

Title