golang web框架 beego 學習 (七)json轉數組

Modulesjson

type User struct {
    Id    int64  `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
    Age   int64  `json:"age"`
}

 

controller數組

func (this *UserController) AddUsers() {
    var obs []md.User // 接收數組
    body := this.Ctx.Input.RequestBody //這是獲取到的json二進制數據
    fmt.Println(body)
    json.Unmarshal(body, &obs) //解析二進制json,把結果放進ob中
    // user := &md.User{Id: ob.UserName, Mobile: ob.Mobile}
    fmt.Println(obs)
    md.CreateUsers(&obs) //這是添加用戶函數
    // if nil != err {
    //     this.Data["json"] = map[string]interface{}{"result": false, "msg": err}
    // } else {
    //     this.Data["json"] = map[string]interface{}{"result": true, "msg": "新增成功"}
    // }
    // this.Data["json"] = map[string]interface{}{"result": false, "msg": err}
    this.Data["json"] = obs
    this.ServeJSON()

}

ORM函數

func CreateUsers(users *[]User) {
    o := orm.NewOrm()
    if successNums, err := o.InsertMulti(len(*users), *users); err != nil {
        fmt.Println("insert fail.....")
    } else {
        fmt.Println("success inserted %d datas", successNums)
    }
}

 另外還有一種傳遞數組的方式,並且應用更普遍:this

Controller:spa

func (this *UserController) AddUsers() {
    var obs []md.User
    body := this.Ctx.Input.RequestBody //這是獲取到的json二進制數據
    fmt.Println(body)
    json.Unmarshal(body, &obs) //解析二進制json,把結果放進ob中
    // user := &md.User{Id: ob.UserName, Mobile: ob.Mobile}

    fmt.Println("Begin AAAAAAAAAAAAAA \n")
    fmt.Println(obs)
    fmt.Println("End   AAAAAAAAAAAAAA \n")

    md.CreateUsers(obs[:]) //這是添加用戶函數
    // if nil != err {
    //     this.Data["json"] = map[string]interface{}{"result": false, "msg": err}
    // } else {
    //     this.Data["json"] = map[string]interface{}{"result": true, "msg": "新增成功"}
    // }
    // this.Data["json"] = map[string]interface{}{"result": false, "msg": err}
    this.Data["json"] = obs
    this.ServeJSON()

}

ORM:code

func CreateUsers(users []User) {

    for i := 0; i < len(users); i++ {
        fmt.Println(users[i])
    }

    o := orm.NewOrm()
    if successNums, err := o.InsertMulti(len(users), users); err != nil {
        fmt.Println("insert fail.....")
    } else {
        fmt.Println("success inserted %d datas", successNums)
    }
}
相關文章
相關標籤/搜索