beego的学习 获取json并解析为对象
beego中,如果我输入一个json,怎么获取这个json并将其解析成对象?
之前学了beego中输出json,之后就想当然地以为:输入也不过如此,应该和spring mvc中和jersey中差不多,能自动映射为对象。
之后才发现完全不是这么一回事。根据官方的文档做,做出来的结果有些莫名其妙,完全没有弄明白是怎么解析的(感觉这个官方例子解释得不太好)。后来我尝试了很久,终于算是尝试出来了。
1.在配置文件app.conf中进行注册
app.conf
1 2 3 4 |
appname = 12.4beego httpport = 8080 runmode = dev copyrequestbody = true |
重要的是这句话:copyrequestbody = true
目的是允许从requestbody中直接获取二进制内容,可以从中读取json
2.写controller
controller.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package controllers import ( "fmt" "encoding/json" "github.com/astaxie/beego" ) type TestJson struct { beego.Controller } type User struct { Id int Username string Password string } func (this *TestJson) TestGetJson() { var ob User json.Unmarshal(this.Ctx.Input.RequestBody, &ob) fmt.Println(ob) this.Ctx.WriteString("success") } |
我的理解:
var ob User定义一个结构ob
this.Ctx.Input.RequestBody解析二进制内容,读取json
json.Unmarshal(this.Ctx.Input.RequestBody, &ob)将json转为ob对象
this.Ctx.WriteString(“success”)返回成功表示
3.注册路由
1 2 3 4 5 6 7 8 9 10 11 |
package routers import ( "12.4beego/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/TestGetJson", &controllers.TestJson{}, `post:TestGetJson`) } |
因为之前写spring mvc和jersey的习惯,这里当然是要限制使用Post的方法来访问接口
4.访问接口
访问http://localhost:8080/TestGetJson
控制台输出如下:
1 2 3 4 |
D:/GOPATH/src/12.4beego/12.4beego.exe [D:/GOPATH/src/12.4beego] 2016/13/18 00:26:24 [asm_amd64.s:1998][I] http server Running on :8080 {1 xie4ever pjl} 2016/13/20 00:27:11 [router.go:829][D] | POST | /TestGetJson | 0 | match | /TestGetJson | |
5.总结
感觉稍微麻烦一点。但是考虑到实现只需要三步走、配置这么少、比较容易理解,感觉beego解析json确实是挺方便的。
你的博客网站很好你好,我最近正在开发一个app要用beego写接口,我想认识你一下,感觉你很优秀,可以加你微信吗,或者你加我也行,我的微信就是我的电话号码:15231430440向你请教一些问题