package main
import (
"encoding/json"
"fmt"
"github.com/goinggo/mapstructure"
)
//把请求包定义成一个结构体
type Requestbody struct {
req string
}
//以指针的方式传入,但在使用时却可以不用关心
// result 是函数内的临时变量,作为返回值可以直接返回调用层
func (r *Requestbody) Json2map() (s map[string]interface{}, err error) {
var result map[string]interface{}
if err := json.Unmarshal([]byte(r.req), &result); err != nil {
return nil, err
}
return result, nil
}
//注意json中不要有_,否则调用 mapstructure.Decode时无法解析
type ConfigStruct struct {
Host string `json:"host"`
Port int `json:"port"`
AnalyticsFile string `json:"analyticsfile"`
StaticFileVersion int `json:"staticfileversion"`
StaticDir string `json:"staticdir"`
TemplatesDir string `json:"templatesdir"`
SerTcpSocketHost string `json:"serTcpSocketHost"`
SerTcpSocketPort int `json:"serTcpSocketPort"`
Fruits []string `json:"fruits"`
}
func main() {
//json转map
var r Requestbody
var s ConfigStruct
var req2map map[string]interface{}
var err error
r.req = `{"host": "http://localhost:9090","port": 9090,"analyticsfile": "","staticfileversion": 1,"staticdir": "E:/Project/goTest/src/","templates_dir": "E:/Project/goTest/src/templates/","serTcpSocketHost": ":12340","serTcpSocketPort": 12340,"fruits": ["apple", "peach"]}`
if req2map, err = r.Json2map(); err != nil {
fmt.Println(err)
}
if err = mapstructure.Decode(req2map, &s); err != nil {
fmt.Println(err)
}
fmt.Println(req2map)
fmt.Printf("%+v", s)
}
import (
"encoding/json"
"fmt"
"github.com/goinggo/mapstructure"
)
//把请求包定义成一个结构体
type Requestbody struct {
req string
}
//以指针的方式传入,但在使用时却可以不用关心
// result 是函数内的临时变量,作为返回值可以直接返回调用层
func (r *Requestbody) Json2map() (s map[string]interface{}, err error) {
var result map[string]interface{}
if err := json.Unmarshal([]byte(r.req), &result); err != nil {
return nil, err
}
return result, nil
}
//注意json中不要有_,否则调用 mapstructure.Decode时无法解析
type ConfigStruct struct {
Host string `json:"host"`
Port int `json:"port"`
AnalyticsFile string `json:"analyticsfile"`
StaticFileVersion int `json:"staticfileversion"`
StaticDir string `json:"staticdir"`
TemplatesDir string `json:"templatesdir"`
SerTcpSocketHost string `json:"serTcpSocketHost"`
SerTcpSocketPort int `json:"serTcpSocketPort"`
Fruits []string `json:"fruits"`
}
func main() {
//json转map
var r Requestbody
var s ConfigStruct
var req2map map[string]interface{}
var err error
r.req = `{"host": "http://localhost:9090","port": 9090,"analyticsfile": "","staticfileversion": 1,"staticdir": "E:/Project/goTest/src/","templates_dir": "E:/Project/goTest/src/templates/","serTcpSocketHost": ":12340","serTcpSocketPort": 12340,"fruits": ["apple", "peach"]}`
if req2map, err = r.Json2map(); err != nil {
fmt.Println(err)
}
if err = mapstructure.Decode(req2map, &s); err != nil {
fmt.Println(err)
}
fmt.Println(req2map)
fmt.Printf("%+v", s)
}
有疑问加站长微信联系(非本文作者)