Go中如何将json文件的内容映射到struct
2018-06-29 本文已影响26人
caoxinyiyi
前言
工作中由于项目需求的需要,将json文件的内容要映射到struct
1、Json文件内容结构的定义
[
{ "GoMethodName":"BasicTypeBool","GoInputParam":{"BasicType":{"boolParam":true}},"JavaReturnData":{"BasicType":{"boolParam":false}},
"JavaMethodName":"testbool","JavaTypes":"boolean","ElemKey":"boolParam","JavaMapKey":"testbool","PtrFlag":false}
]
2、Struct结构体的定义
type BasicType struct {
BoolParam bool `json:"boolParam"`
ByteParam byte `json:"byteParam"`
Uint8Param uint8 `json:"uint8Param"`
CharParam string `json:"charParam"`
ShortParam int16 `json:"shortParam"`
IntParam int32 `json:"intParam"`
LongParam int64 `json:"longParam"`
Long2Param int `json:"long2Param"`
FloatParam float32 `json:"floatParam"`
DoubleParam float64 `json:"doubleParam"`
StringParam string `json:"stringParam"`
}
type DataJsonStruct struct {
GoMethodName string
GoInputParam struct {
BasicType BasicType `json:"BasicType"`
} `json:"GoInputParam"`
JavaReturnData struct {
BasicType BasicType `json:"BasicType"`
} `json:"JavaReturnData"`
JavaMethodName string
JavaTypes string
ElemKey string
JavaMapKey string
PtrFlag bool
}
3、如何映射代码
package Test
import (
"fmt"
"encoding/json"
)
//将json解析到struct
func JsonParseToStruct(jsonPath string) []DataJsonStruct{
var dat []DataJsonStruct
//基本类型测试数据json
DataJsonStruct := readTestDataFile(jsonPath)
fmt.Println(DataJsonStruct)
//解析json
err := json. Unmarshal ( [ ] byte (DataJsonStruct), &dat )
if err != nil {
fmt. Println ( "error:" , err )
}
fmt. Printf ( "%+v" , dat )
for _, v := range dat {
fmt.Printf("\n %v",v)
}
return dat
}
//读取测试数据的文件内容
func readTestDataFile(path string) string{
fi, err := os.Open(path)
if err != nil {
panic(err)
}
defer fi.Close()
fd, err := ioutil.ReadAll(fi)
return string(fd)
}