为了账号安全,请及时绑定邮箱和手机立即绑定

如何解析json post请求

如何解析json post请求

Go
BIG阳 2023-05-15 10:31:43
我想将 json 数据发布到 Go api,但我无法在 Go 中解析 jsonjavascript代码:data= {"user":{"username":"admin","password":"123"},"profile":{"firstname":"morteza","lastname":"khadem","files":["/temp/a.jpg","/temp/b.jpg"]}}$.post('/parse-json', data, function () {    alert('success');});在 php 中获取数据非常简单 ($_REQUEST['user']['firstname']) 但在 Go 中不同
查看完整描述

3 回答

?
慕娘9325324

TA贡献1783条经验 获得超4个赞

GO 不同于 PHP 和 JS。它不是易于使用,而是专注于明确和可靠。


要在请求中解析 JSON 主体,我们应该有强类型结构定义来描述接收有效负载的结构。这就是我们如何控制应该支持的字段。这很重要,因为每个文件都有自己的类型,如果来自请求的字符串与该类型不匹配,解析将失败。


type RequestBody struct {

    User   User  `json:"user"`

    Profile Profile `json:"profile"`

}


type User struct {

    UserName   string  `json:"username"`

    Password string `json:"password"`

}


type Profile struct {

    FirstName   string  `json:"firstname"`

    LastName string `json:"lastname"`

    Files []string `json:"files"`

}



func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    decoder := json.NewDecoder(r.Body)

    var req RequestBody

    err := decoder.Decode(&req)

    if err != nil {

        // log error and return 400 to caller

        return

    }


    // Use req

}


查看完整回答
反对 回复 2023-05-15
?
浮云间

TA贡献1829条经验 获得超4个赞

现在我使用这段代码:


type Merchant struct{}


func (*Merchant) Register(context context.Context){

    type registerRequestData struct{

        Merchant models.MrtMerchant `json:"merchant"`

        User models2.UsrUser `json:"user"`

        Profile models2.UsrUserProfile `json:"profile"`

        Branch models.MrtMerchantBranch `json:"branch"`

    }

    var request registerRequestData

    if err:=context.ReadJSON(&request);err!=nil{

        panic(err)

    }


    fmt.Printf("%+v\n",request)

}


查看完整回答
反对 回复 2023-05-15
?
隔江千里

TA贡献1906条经验 获得超10个赞

如果使用 iris 框架,你可以像这样使用 ReadJSON 函数:


func serve(context context.Context){

    var request map[string]interface{}

    context.ReadJSON(request)

    username:=request["user"].(map[string]string)["username"]

    fmt.Println(username)

}


查看完整回答
反对 回复 2023-05-15
  • 3 回答
  • 0 关注
  • 120 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信