beego之json重新打包

来源:互联网 发布:tp-link产品工程师知乎 编辑:程序博客网 时间:2024/06/03 13:14
最近的一个需求是,去读取数据库的数据,但是里面有一个字段本来应该是json来存的,但是由于存储方便,直接把它变成字符,在后台提取处理的时候才吧它变回json。我在这里是用json存储提取到的struct里存储。但是后面需要在这个json添加json数组。由于对golang中的struct操作不熟悉,这里搞了我2天。其实里面就是涉及到slice的操作。因为在结构体中,定义jsong数组是
type Gwlog struct {
    Acname            string
    Ip                string
    Auth_clients      string
    Ap_num            string
    Online_ap         string
    Offline_ap        string
    Timestarp         string
    Gwid              string
    Arp_num           string
    Offline_ap_status string
    Aplist            []Offlineapmsg

}

其中Aplist就是json数组,它的定义就是slice,所以如果需要添加json数组,直接用append就可以了,具体beego代码如下:

package controllersimport ("encoding/json""fmt""strings""time""github.com/astaxie/beego""github.com/astaxie/beego/orm"_ "github.com/go-sql-driver/mysql")type Gwlog struct {A            stringB            []Offlineapmsg}type Offlineapmsg struct {Mac    stringIp     stringApname string}func init() {orm.RegisterDriver("mysql", orm.DRMySQL)orm.RegisterDataBase("rou", "mysql", "root:newpasswd@tcp(localhosg:33306)/yk_log?charset=utf8")}type RouController struct {beego.Controller}func (c *RouController) Get() {o := orm.NewOrm()o.Using("rou")var gwmsgs []Gwlogvar j int64num, err := o.Raw("select *from ac_status").QueryRows(&gwmsgs)if err != nil {fmt.Println("user nums: ", err)}for j = 0; j < num; j++ {offline_ap_msg_every := strings.Split(gwmsgs[j].Offline_ap_status, ";")for i := 0; i < len(offline_ap_msg_every); i++ {offline_ap_msg_each := strings.Split(offline_ap_msg_every[i], ",")if len(offline_ap_msg_each) == 1 {fmt.Println("continue")continue}gwmsgs[j].Aplist = append(gwmsgs[j].Aplist, Offlineapmsg{Mac: offline_ap_msg_each[1], Ip: offline_ap_msg_each[2], Apname: offline_ap_msg_each[0]})}}c.Data["json"] = gwmsgsc.ServeJSON()}


0 0
原创粉丝点击