Last active
November 24, 2022 09:00
-
-
Save miguelmota/04252b346d281b93f047bf9a20f73f04 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