Go 개발 Struct 를 map 로 전환 하 는 두 가지 방식 비교
mport (
"encoding/json"
"fmt"
"reflect"
"time"
)
type Persion struct {
Id int
Name string
Address string
Email string
School string
City string
Company string
Age int
Sex string
Proviece string
Com string
PostTo string
Buys string
Hos string
}
func main() {
StructToMapViaJson()
//StructToMapViaReflect()
}
func StructToMapViaJson() {
m := make(map[string]interface{})
t := time.Now()
person := Persion{
Id: 98439,
Name: "zhaondifnei",
Address: " ",
Email: "[email protected]",
School: " ",
City: "zhongguoguanzhou",
Company: "sndifneinsifnienisn",
Age: 23,
Sex: "F",
Proviece: "jianxi",
Com: " ",
PostTo: " XXXXXXXX",
Buys: "shensinfienisnfieni",
Hos: "zhonsndifneisnidnfie",
}
j, _ := json.Marshal(person)
json.Unmarshal(j, &m)
fmt.Println(m)
fmt.Println(time.Now().Sub(t))
}
1. struct 를 통 해 json, json 을 map 로 전환
func StructToMapViaJson() {
m := make(map[string]interface{})
t := time.Now()
person := Persion{
Id: 98439,
Name: "zhaondifnei",
Address: " ",
Email: "[email protected]",
School: " ",
City: "zhongguoguanzhou",
Company: "sndifneinsifnienisn",
Age: 23,
Sex: "F",
Proviece: "jianxi",
Com: " ",
PostTo: " XXXXXXXX",
Buys: "shensinfienisnfieni",
Hos: "zhonsndifneisnidnfie",
}
j, _ := json.Marshal(person)
json.Unmarshal(j, &m)
fmt.Println(m)
fmt.Printf("duration:%d", time.Now().Sub(t))
}
출력: map [Proviece: jianxi Com: 광저우 람 보 르 기니 Hos: zhonsndifneisnidnfie Name: zhaondifnei Company: sndifneinsifninisn Buys: shensinfieni 나이: 23 PostTo: 푸 른 고래 XXXXX XXXX 주소: 대사 지 학교: 광저우 제1 5 중학교 도시: zhongguoguanzhou Sex: F Id: 98439 이메일:[email protected]] duration:250467
2. 반사 형식 으로 맵 생 성
func StructToMapViaReflect() {
m := make(map[string]interface{})
t := time.Now()
person := Persion{
Id: 98439,
Name: "zhaondifnei",
Address: " ",
Email: "[email protected]",
School: " ",
City: "zhongguoguanzhou",
Company: "sndifneinsifnienisn",
Age: 23,
Sex: "F",
Proviece: "jianxi",
Com: " ",
PostTo: " XXXXXXXX",
Buys: "shensinfienisnfieni",
Hos: "zhonsndifneisnidnfie",
}
elem := reflect.ValueOf(&person).Elem()
relType := elem.Type()
for i := 0; i < relType.NumField(); i++ {
m[relType.Field(i).Name] = elem.Field(i).Interface()
}
fmt.Println(m)
fmt.Printf("duration:%d", time.Now().Sub(t))
}
출력: map [Buys: shensinfienisnfienfieni Name: zhaondifnei City: zhongguoguanzhou Sex: F Proviece: jianxi Com: 광저우 람 보 르 기니 Id: 98439 학교: 광저우 제1 5 중학교 주소: 대사 지 나이: 23 게시 물: 푸 른 고래 XXXXX XXXX 호: zhonsndifneisnidnfie 이메일:[email protected] Company:sndifneinsifnienisn] duration:104239
결론.
비 교 를 통 해 알 수 있 듯 이 반사 적 인 형식 전환 은 기본적으로 제 이 슨 형식 으로 전환 하 는 두 배 이다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.