You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
33 lines
621 B
Go
33 lines
621 B
Go
1 year ago
|
package main
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
)
|
||
|
|
||
|
type Person struct {
|
||
|
Name string
|
||
|
Addr string
|
||
|
Phone string
|
||
|
}
|
||
|
|
||
|
func main() {
|
||
|
|
||
|
p1 := Person{Name: "Drew", Addr: "123 Fake Street", Phone: "8675309"}
|
||
|
byte_array, err := json.Marshal(p1) // returns json as a slice of bytes []bytes
|
||
|
if err != nil {
|
||
|
fmt.Println("Damn it")
|
||
|
}
|
||
|
fmt.Println(byte_array)
|
||
|
fmt.Println(p1)
|
||
|
|
||
|
// Unmarshaling going from a json byte array to a to a go object
|
||
|
p2 := Person{}
|
||
|
err = json.Unmarshal(byte_array, &p2) // will throw an error if the byte array doesn't fit the struct
|
||
|
if err != nil {
|
||
|
fmt.Println("Damn it")
|
||
|
}
|
||
|
|
||
|
fmt.Println(p2)
|
||
|
}
|