-
-
Save YagmurOzden/026e8fb1252c7e2d275862ca642647e8 to your computer and use it in GitHub Desktop.
Golang JSON Marshal (struct to string) (M for "Make json") and Unmarshal (string to struct) (U for "Unmake json") example
This file contains 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" | |
) | |
func main() { | |
type MyStruct struct { | |
Message string `json:"message"` | |
} | |
mystruct := &MyStruct{ | |
Message: "hello", | |
} | |
// convert struct to json string | |
jsonBytes, err := json.Marshal(mystruct) | |
fmt.Println(string(jsonBytes), err) // {"message":"hello"} <nil> | |
var mystruct_2 *MyStruct | |
// convert json string to struct | |
err = json.Unmarshal(jsonBytes, &mystruct_2) | |
fmt.Println(mystruct_2, err) // &{hello} <nil> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment