4 回答
TA贡献1830条经验 获得超3个赞
我看到你是JSON。可以将 JSON 直接解码为结构实例。
我将构建类似于以下代码片段的代码:
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贡献1936条经验 获得超6个赞
我看到你是JSON。可以将 JSON 直接解码为结构实例。
我将构建类似于以下代码片段的代码:
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贡献1830条经验 获得超9个赞
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贡献1831条经验 获得超10个赞
使用来自 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 关注
- 87 浏览
添加回答
举报