Created
July 20, 2017 21:55
-
-
Save aren55555/c4c0a8151146c1014beeac560de7fe5b to your computer and use it in GitHub Desktop.
Embedded Marshal/Unmarshal
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" | |
) | |
type Foo struct { | |
Bar | |
Name string | |
} | |
type Bar struct { | |
Name int | |
} | |
func main() { | |
f := &Foo{ | |
Name: "foo", | |
Bar: Bar{ | |
Name: 5, | |
}, | |
} | |
b, err := json.Marshal(f) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(string(b)) | |
d := map[string]interface{}{ | |
"Name": 5, | |
} | |
b, _ = json.Marshal(d) | |
f = &Foo{} | |
err = json.Unmarshal(b, f) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println(f) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment