1 在beego app.conf配置文件中设置
#开启获取JSON/Request Body 里的内容
copyrequestbody = true
2 json 样例
{
"Data": [{
"P_nian_fen": "2018",
"P_sheng_fen": "11",
"P_zhuan_ye": "22",
"P_lei_xing": "二批次",
"P_max_score": "500",
"P_min_score": "400",
"P_average_score": "450"
},
{
"P_nian_fen": "2018",
"P_sheng_fen": "北京",
"P_zhuan_ye": "软件工程",
"P_lei_xing": "二批次",
"P_max_score": "500",
"P_min_score": "400",
"P_average_score": "450"
}
]
}
3 在controller中使用Golang标准库json包来解析json数据封装到stuct结构体
注意:结构体中的变量名需要同json内的字段名一致,顺序可以不一致,整体结构需要一致。
package InformationInput
import (
"../../models"
"encoding/json"
"fmt"
"github.com/astaxie/beego"
)
type InputMainController struct {
beego.Controller
}
func (c *InputMainController) InputPScore() {
//定义存放 Json内 Data 内的列表数据
type T1_pscore struct {
P_sheng_fen string
P_lei_xing string
P_zhuan_ye string
P_max_score string
P_min_score string
P_average_score string
P_nian_fen string
}
//定义整个json 数据的结构体
type T2_pscore struct {
Data []T1_pscore // data列表为多个
}
temp:=T2_pscore{}
data1 := c.Ctx.Input.RequestBody //在RequestBody中读取Json
fmt.Println(data1)
err := json.Unmarshal(data1, &temp) //还原Json对象数据 解析到temp中
fmt.Println(err)
fmt.Println(temp)
}
4 在postma中测试接口
1.选择“POST”方式
2 点击"body",’‘raw’'并设定为JSON
3 接着添加:Json