Golang struct,map,json transposition

This paper is used to record the type conversion problems I encountered in the Golang learning stage, aiming at the conversion problems among JSON, map and struct, and using three class libraries of technology JSON, MapStructure and Reflect

Common 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": Dimpled pig."address":   []map[string]interface{} {{"address": "address01"}, {"address": "address02"}}},var User UserInfoVo

func init(a) {
	User = UserInfoVo{
		Id:       "01",
		UserName: Dimpled pig,
		Address: []AddressVo{
			{
				Address: "Hunan",
			},
			{
				Address: "Beijing",},},}}Copy the code

I. Map, struct mutual transfer

1. Turn the map struct

There are two ways to convert a map to a struct

1. The packet github.com/mitchellh/mapstructure is through a third party

2. Convert map to JSON, and then convert json to struct

Third-party package MapStructure

Download dependencies and convert them through third-party dependencies

go get github.com/goinggo/mapstructure

func TestMapToStructByMod(t *testing.T) {
	var afterStruct =UserInfoVo{}
	before := time.Now()
	err := mapstructure.Decode(beforeMap, &afterStruct)
	iferr! =nil{
		fmt.Println(err)
	}
	fmt.Printf("result:%+v \n",time.Since(before))
	fmt.Printf("result:%+v \n",afterStruct)
}
Copy the code
Result :61.757µs result:{Id:123 UserName: Address:[{Address:address01} {Address:address02}]} -- PASS: PASS TestMapToStructByMod (0.00 s)Copy the code

Convert through JSON

Map is converted to JSON, and then converted to struct via JSON

It’s a little bit cumbersome

func TestMapToStructByJson(t *testing.T) {
	beforeMap := map[string]interface{} {"id":"123"."user_name":Dimpled pig."address": []map[string]interface{} {{"address": "address01"}, {"address": "address02"}}},var afterStruct =UserInfoVo{}
	before := time.Now()
	marshal, err := json.Marshal(beforeMap)
	iferr! =nil{
		fmt.Println("marshal:",err)
		return
	}
	err = json.Unmarshal(marshal, &afterStruct)
	iferr! =nil{
		fmt.Println("unmarshal:",err)
		return
	}
	fmt.Println(time.Since(before))
	fmt.Printf("resutlt: %+v",afterStruct)
}
Copy the code
Address:[{Address:address01} {Address:address02}]}-- PASS: PASS TestMapToStructByJson (0.00 s)Copy the code

conclusion

Question:

Which is better in terms of performance?

According to the result

Using JSON takes 134.299µs

The time required to use mapstructure is 61.757µs

It turns out that using the third-party package MapStructure performs better, so why? Press the button for the moment

2. Struct to map

JSON serialization conversion

The struct is first converted into a byte array, and then the byte array is converted into a map for printing

func TestStructToMapByJson(t *testing.T) {
	var resultMap interface{}
	before := time.Now()
	jsonMarshal, _ := json.Marshal(User)
	err := json.Unmarshal(jsonMarshal, &resultMap)
	iferr ! =nil {
		fmt.Println(err)
		return
	}
	fmt.Println(time.Since(before))
	fmt.Printf("%+v",resultMap)
}
Copy the code
158.857µs map[address:[map[address: 中 国] map[address: Beijing]] ID :01 user_name: Dimplepig]-- PASS: TestStructToMapByJson (0.00s) PASSCopy the code

By reflection

Get the type and value of User by reflection

func TestStructToMapByReflect(t *testing.T) {
	var resultMap = make(map[string]interface{},10)
	before := time.Now()

	ty:=reflect.TypeOf(User)
	v:=reflect.ValueOf(User)
	for i := 0; i < v.NumField(); i++ {
		resultMap[strings.ToLower(ty.Field(i).Name)]=v.Field(i).Interface()
	}
	fmt.Println(time.Since(before))
	fmt.Printf("%+v",resultMap)
}
Copy the code
13.965µ S map[address:[{address: hU} {address: Beijing}] ID :01 username: Dimplepig]-- PASS: TestStructToMapByReflect (0.00s) PASSCopy the code

conclusion

Question: Which is better in terms of performance?

The answer is that it’s faster to use reflection, it’s not as much of a conversion, remember that when you initialize the size in make, I tried it out, and it takes 3 to 4µs to specify the size

Another way to do this on the network is to use structs packages, but I looked at the dependencies and found that they haven’t been updated in three years

2, struct, JSON mutual transfer

1. Turn json struct

func TestStructToJsonByJson(t *testing.T) {
	before := time.Now()
	marshal, _ := json.Marshal(User)
	fmt.Println(time.Since(before))
	fmt.Printf("%s", marshal)
}
Copy the code
116.068 (including s {" id ":" 01 ", "user_name" : "dimples pig", "address" : [{" address ", "hunan"}, {" address ":" Beijing "}]} - PASS: PASS TestStructToJsonByJson (0.00 s)Copy the code

2. Turn the json struct

func TestJsonToStructByJson(t *testing.T) {
	info:=UserInfoVo{}
	marshal, _ := json.Marshal(User)
	before := time.Now()
	json.Unmarshal(marshal,&info)
	fmt.Println(time.Since(before))
	fmt.Printf("%+v",info)
}
Copy the code
Address:[{Address: Address} {Address: Beijing}]}-- PASS: TestJsonToStructByJson (0.00s) PASSCopy the code

Map, JSON interchange

1. Turn the map json

func TestMapToJson(t *testing.T) {
	before := time.Now()
	marshal, _ := json.Marshal(beforeMap)
	fmt.Println(time.Since(before))
	fmt.Printf("%s", marshal)
}
Copy the code
{75.133 (including s "address" : [{" address ":" address01 "}, {" address ":" address02}], "id" : "123", "user_name" : "dimples pig"} - PASS: PASS TestMapToJson (0.00 s)Copy the code

2. Turn the map json

func TestJsonToMap(t *testing.T) {
	marshal, _ := json.Marshal(beforeMap)
	resultMap:=make(map[string]interface{},10)
	before := time.Now()
	json.Unmarshal(marshal,&resultMap)
	fmt.Println(time.Since(before))
	fmt.Printf("%+v", resultMap)
}
Copy the code
28.728µs map[address:[map[address:address01] map[address:address02]] ID :123 user_name: Dimple pig]-- PASS: PASS TestJsonToMap (0.00 s)Copy the code

conclusion

The conversion between the three is more about using json libraries, only in map to struct using MapStructure, struct to Map using reflection, other transformations, more use json built-in libraries for conversion

This article is published by OpenWrite!