Created
July 24, 2021 11:18
-
-
Save irmorteza/f5782ab36530630f92ecba1a6ea51c22 to your computer and use it in GitHub Desktop.
go sample: how to convert Struct to map or json and vice versa
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "encoding/json" | |
| "fmt" | |
| ) | |
| type MyStruct struct { | |
| Id string `json:"id"` | |
| Name string `json:"name"` | |
| UserId string `json:"user_id"` | |
| CreatedAt int64 `json:"created_at"` | |
| } | |
| func (c *MyStruct) ToMAP() (res map[string]interface{}){ | |
| a, err := json.Marshal(c) | |
| if err != nil { | |
| panic(err) | |
| } | |
| json.Unmarshal(a, &res) | |
| return | |
| } | |
| func (c *MyStruct)LoadFromMap(m map[string]interface{}) error{ | |
| data, err := json.Marshal(m) | |
| if err == nil{ | |
| err = json.Unmarshal(data, c) | |
| } | |
| return err | |
| } | |
| func (c *MyStruct) ToJSON() string { | |
| a, err := json.Marshal(c) | |
| if err != nil { | |
| panic(err) | |
| } | |
| return string(a) | |
| } | |
| func (c *MyStruct)LoadFromJSON(jsonStr string) error{ | |
| err := json.Unmarshal([]byte(jsonStr), c) | |
| return err | |
| } | |
| func (c *MyStruct)ToByte() ([]byte, error){ | |
| return json.Marshal(c) | |
| } | |
| func (c *MyStruct)LoadFromByte(data []byte) error{ | |
| return json.Unmarshal(data, c) | |
| } | |
| func main() { | |
| s1 := MyStruct{ | |
| Id: "2", | |
| Name:"jack", | |
| UserId: "123", | |
| CreatedAt: 5, | |
| } | |
| fmt.Println("struct to byte:") | |
| fmt.Println(s1.ToByte()) | |
| fmt.Println() | |
| fmt.Println("struct to map[string]interface{}:") | |
| fmt.Println(s1.ToMAP()) | |
| fmt.Println() | |
| fmt.Println("struct to string json: ") | |
| fmt.Println(s1.ToJSON()) | |
| fmt.Println() | |
| /////////////////////////////////////// | |
| /////////////////////////////////////// | |
| // load from map | |
| fmt.Println("here, sample of load from map:") | |
| m := map[string]interface{}{ | |
| "id": "3", | |
| "name": "Steve", | |
| "user_id": "114", | |
| "created_at": 5, | |
| } | |
| s2 := MyStruct{} | |
| s2.LoadFromMap(m) | |
| fmt.Println(s2) | |
| /////////////////////////////////////// | |
| /////////////////////////////////////// | |
| // load from json string | |
| fmt.Println("here, sample of load from json string:") | |
| jsonStr := "{\"id\":\"4\",\"name\":\"james\",\"user_id\":\"125\",\"created_at\":5}" | |
| s3 := MyStruct{} | |
| s3.LoadFromJSON(jsonStr) | |
| fmt.Println(s3) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment