Forked from tejainece/marshall_slice_map_in_struct.go
Created
November 12, 2021 10:05
-
-
Save cnekmp/70fa8607b0e69d5a502b8f8667566bbe to your computer and use it in GitHub Desktop.
Marshall slice and map members of a struct into JSON in Golang.
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 ( | |
"fmt" | |
"encoding/json" | |
) | |
type Data struct { | |
IntF int | |
StringF string | |
FloatF float64 | |
SliceF []string | |
MapF map[string]int | |
} | |
func (d Data) print() { | |
fmt.Printf("IntF: %d\n", d.IntF) | |
fmt.Printf("StringF: %s\n", d.StringF) | |
fmt.Printf("FloatF: %f\n", d.FloatF) | |
fmt.Printf("SliceF: %s\n", d.SliceF) | |
fmt.Printf("MapF: %s\n", d.MapF) | |
} | |
func main() { | |
//Marshaling example | |
fmt.Printf("Before marshaling:\n") | |
data := Data{5, "55", 55.5, []string{"5", "55", "555"}, map[string]int{"5":5, "55":55, "555":555}} | |
data.print() | |
b, _ := json.Marshal(data) | |
fmt.Printf("\nMarshalled data: %s\n", b) | |
//Unmarshaling example | |
var jsonStr = `{"IntF":555,"StringF":"5","FloatF":5.555,"SliceF":["555","55","5"],"MapF":{"5.5":5.5,"55.5":55.5,"555.5":555.5}}` | |
fmt.Printf("\n\nUnmarshaled data:\n%s\n", jsonStr) | |
var jsonByte []byte = []byte(jsonStr) | |
var unmarData Data | |
json.Unmarshal(jsonByte, &unmarData) | |
fmt.Printf("\nAfter unmarshaling\n") | |
unmarData.print() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment