第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何解析json post請求

如何解析json post請求

Go
BIG陽 2023-05-15 10:31:43
我想將 json 數(shù)據(jù)發(fā)布到 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 中獲取數(shù)據(jù)非常簡單 ($_REQUEST['user']['firstname']) 但在 Go 中不同
查看完整描述

3 回答

?
慕娘9325324

TA貢獻1783條經(jīng)驗 獲得超4個贊

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


要在請求中解析 JSON 主體,我們應該有強類型結(jié)構(gòu)定義來描述接收有效負載的結(jié)構(gòu)。這就是我們?nèi)绾慰刂茟撝С值淖侄?。這很重要,因為每個文件都有自己的類型,如果來自請求的字符串與該類型不匹配,解析將失敗。


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條經(jīng)驗 獲得超4個贊

現(xiàn)在我使用這段代碼:


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條經(jīng)驗 獲得超10個贊

如果使用 iris 框架,你可以像這樣使用 ReadJSON 函數(shù):


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 關(guān)注
  • 204 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號