4 回答
TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超3個(gè)贊
我看到你是JSON??梢詫?JSON 直接解碼為結(jié)構(gòu)實(shí)例。
我將構(gòu)建類似于以下代碼片段的代碼:
type ALiNotifyLog struct {
// your fields here
}
func parseRequest(r *http.Request) {
var notifyLog ALiNotifyLog
err := json.NewDecoder(r.Body).Decode(¬ifyLog)
if err != nil {
// do something
}
// ............ more code
}
func SaveData(data ALiNotifyLog) {
res := global.Orm.Table(paynotifylog).Create(&data)
fmt.Println(res)
// ........... more code
}
TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
我看到你是JSON。可以將 JSON 直接解碼為結(jié)構(gòu)實(shí)例。
我將構(gòu)建類似于以下代碼片段的代碼:
type ALiNotifyLog struct {
// your fields here
}
func parseRequest(r *http.Request) {
var notifyLog ALiNotifyLog
err := json.NewDecoder(r.Body).Decode(¬ifyLog)
if err != nil {
// do something
}
// ............ more code
}
func SaveData(data ALiNotifyLog) {
res := global.Orm.Table(paynotifylog).Create(&data)
fmt.Println(res)
// ........... more code
}
TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊
go get https://github.com/mitchellh/mapstructure
package main
import (
"log"
"os"
"github.com/mitchellh/mapstructure"
)
type MyStruct struct {
This int
That string `json:"thaaaaat"`
}
func main() {
var result map[string]interface{}
cfg := &mapstructure.DecoderConfig{
TagName: "json",
Result: &result,
}
decoder, err := mapstructure.NewDecoder(cfg)
if err != nil {
log.Printf("Could not create decoder: %v", err)
os.Exit(1)
}
myData := &MyStruct{
This: 42,
That: "foobar",
}
err = decoder.Decode(myData)
if err != nil {
log.Printf("Decoding failed: %v", err)
os.Exit(1)
}
log.Print(cfg.Result)
}
輸出:
&map[This:42 thaaaaaat:foobar]
https://go.dev/play/p/mPK_9fEevyC
TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超10個(gè)贊
使用來自 GitHub的包mapstructure。
go get https://github.com/mitchellh/mapstructure
package main
import (
"log"
"os"
"github.com/mitchellh/mapstructure"
)
type MyStruct struct {
This int
That string `json:"thaaaaat"`
}
func main() {
var result map[string]interface{}
cfg := &mapstructure.DecoderConfig{
TagName: "json",
Result: &result,
}
decoder, err := mapstructure.NewDecoder(cfg)
if err != nil {
log.Printf("Could not create decoder: %v", err)
os.Exit(1)
}
myData := &MyStruct{
This: 42,
That: "foobar",
}
err = decoder.Decode(myData)
if err != nil {
log.Printf("Decoding failed: %v", err)
os.Exit(1)
}
log.Print(cfg.Result)
}
輸出:
&map[This:42 thaaaaaat:foobar]
https://go.dev/play/p/mPK_9fEevyC
- 4 回答
- 0 關(guān)注
- 151 瀏覽
添加回答
舉報(bào)
