This article is used to record the type conversion problem I encountered in the golang learning stage. It targets the problem of mutual conversion between json, map, and struct. The technologies used are json, mapstructure, and reflect.
Public code area
package main import ( "encoding/json" "fmt" "testing" ) type UserInfoVo struct { Id string `json:"id"` UserName string `json:"user_name"` Address []AddressVo `json:"address"` } type AddressVo struct { Address string `json:"address"` } var beforeMap = map[string]interface{}{ "id": "123", "user_name": "Dimmill Pig", "address": []map[string]interface{}{{"address": "address01"}, {"address": "address02"}}, } var User UserInfoVo func init() { User = UserInfoVo{ Id: "01", UserName: "Dimmill Pig", Address: []AddressVo{ { Address: "Hunan", }, { Address: "Beijing", }, }, } }
1. map, struct mutual transfer
Turn struct
There are two ways to convert map to struct
1. It is through the third-party package /mitchellh/maplanture
2. Turn json through map, and then turn struct through json
Third-party package mapstructure
Download dependencies, convert them through third-party dependencies
go get /goinggo/mapstructure
func TestMapToStructByMod(t *) { var afterStruct =UserInfoVo{} before := () err := (beforeMap, &afterStruct) if err!=nil{ (err) } ("result:%+v \n",(before)) ("result:%+v \n",afterStruct) }
result:61.757µs
result:{Id:123 UserName: Address:[{Address:address01} {Address:address02}]}
--- PASS: TestMapToStructByMod (0.00s)
PASS
Convert via JSON
First convert map to JSON, and then convert JSON to struct
A bit cumbersome
func TestMapToStructByJson(t *) { beforeMap := map[string]interface {}{ "id":"123", "user_name":"Dimmill Pig", "address":[]map[string]interface{}{{"address": "address01"}, {"address": "address02"}}, } var afterStruct =UserInfoVo{} before := () marshal, err := (beforeMap) if err!=nil{ ("marshal:",err) return } err = (marshal, &afterStruct) if err!=nil{ ("unmarshal:",err) return } ((before)) ("resutlt: %+v",afterStruct) }
134.299µs
resutlt: {Id:123 UserName:Dimi Pig Address:[{Address:address01} {Address:address02}]}--- PASS: TestMapToStructByJson (0.00s)
PASS
Summarize
question:
Which one is better in performance?
Answer based on the results
The time required to use JSON is 134.299µs
The time required to use mapstructure is 61.757µs
The result is that using the third-party package mapstructure performs better, so, why? Press to not to count
2. struct to map
JSON serialization conversion
First convert struct into byte array, then convert byte array into map print
func TestStructToMapByJson(t *) { var resultMap interface{} before := () jsonMarshal, _ := (User) err := (jsonMarshal, &resultMap) if err != nil { (err) return } ((before)) ("%+v",resultMap) }
158.857µs
map[address:[map[address:Hunan] map[address:Beijing]] id:01 user_name:Dimi Pig]--- PASS: TestStructToMapByJson (0.00s)
PASS
Convert by reflection
Get the User's type and value through reflection
func TestStructToMapByReflect(t *) { var resultMap = make(map[string]interface{},10) before := () ty:=(User) v:=(User) for i := 0; i < (); i++ { resultMap[((i).Name)]=(i).Interface() } ((before)) ("%+v",resultMap) }
13.965µs
map[address:[{Address:Hunan} {Address:Beijing}] id:01 username:Dimi Pig]--- PASS: TestStructToMapByReflect (0.00s)
PASS
Summarize
Question: Which one is better in terms of performance?
The answer is to use reflection faster, there are not so many cumbersome conversions, remember to initialize the size in make, I tried it, there is a difference between not specifying the size and specifying the size in time.
Another way to use the structs package on the Internet, but I looked at it and found that the dependency package has not been updated for three years.
2. struct, json mutual transfer
1. struct to json
func TestStructToJsonByJson(t *) { before := () marshal, _ := (User) ((before)) ("%s", marshal) }
116.068µs
{"id":"01","user_name":"Dimeropig","address":[{"address":"Hunan"},{"address":"Beijing"}]}--- PASS: TestStructToJsonByJson (0.00s)
PASS
Turn struct
func TestJsonToStructByJson(t *) { info:=UserInfoVo{} marshal, _ := (User) before := () (marshal,&info) ((before)) ("%+v",info) }
23.009µs
{Id:01 UserName:Dimi Pig Address:[{Address:Hunan} {Address:Beijing}]}--- PASS: TestJsonToStructByJson (0.00s)
PASS
3. Map, json transfer
Turn to json
func TestMapToJson(t *) { before := () marshal, _ := (beforeMap) ((before)) ("%s", marshal) }
75.133µs
{"address":[{"address":"address01"},{"address":"address02"}],"id":"123","user_name":"Dimmug Pig"}--- PASS: TestMapToJson (0.00s)
PASS
Turn to map
func TestJsonToMap(t *) { marshal, _ := (beforeMap) resultMap:=make(map[string]interface{},10) before := () (marshal,&resultMap) ((before)) ("%+v", resultMap) }
28.728µs
map[address:[map[address:address01] map[address:address02]] id:123 user_name:Dimi Pig]--- PASS: TestJsonToMap (0.00s)
PASS
Summarize
The conversion between the three is more about if you use the json library, you can only use map structure when map is used, struct is used to map, and other conversions are used to convert it with the json built-in library.
This is the end of this article about the mutual conversion between golang struct, map, and json. For more related golang struct, map, and json, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!