golang web框架 beego 学习 (七)json转数组
Modules
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) } }
另外还有一种传递数组的方式,而且应用更广泛:
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("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:
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) } }