- Marshal => String
- Encode => Stream
Marshal and Unmarshal convert a string into JSON and vice versa.
Encoding and decoding convert a stream into JSON and vice versa.
The below code show working of marshal and unmarshal
type Person struct {
First string
Last string
}
func main() {
/* This will marshal the JSON into []bytes */
p1 := Person{"alice", "bob"}
bs, _ := json.Marshal(p1)
fmt.Println(string(bs))
/* This will unmarshal the JSON from []bytes */
var p2 Person
bs = []byte(`{"First":"alice","Last":"bob"}`)
json.Unmarshal(bs, &p2)
fmt.Println(p2)
}
Encoder and decoder write struct to slice of a stream or read data from a slice of a stream and convert it into a struct. Internally, it also implements the marshal method. The only difference is if you want to play with string or bytes use marshal, and if any data you want to read or write to some writer interface, use encodes and decode.