如何解析 json post 请求

How to parse json post request

我想postjson数据去Goapi,但是我无法在Gojson中解析json

javascript代码:

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中不同

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
}

如果使用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)
}

现在我使用这个代码:

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)
}