scott_luffy
1 min readJun 13, 2020

Marshal & Unmarshal in golang

Marshal & Unmarshal are widely used, especially in data transmission. Here I’m going to talk about how to use it in golang:

First, let’s get a review of the API

package: encoding/json

func Marshal(v interface{}) ([]byte, error)func Unmarshal(data []byte, v interface{}) error

Marshal returns the JSON encoding of v.

Marshal traverses the value v recursively. If an encountered value implements the Marshaler interface and is not a nil pointer, Marshal calls its MarshalJSON method to produce JSON. If no MarshalJSON method is present but the value implements encoding.TextMarshaler instead, Marshal calls its MarshalText method and encodes the result as a JSON string. The nil pointer exception is not strictly necessary but mimics a similar, necessary exception in the behavior of UnmarshalJSON.

Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

example 1:

package mainimport (
"encoding/json"
"fmt"
)
type Student struct {
Name string
Age int
}
func main() {s1 := &Student{"Amanda", 12}bytes_s1, err := json.Marshal(s1)
if err != nil {
panic(err)
}
fmt.Println(string(bytes_s1)) //{"Name":"Amanda","Age":12}
var s2 string = `{"name":"Judy","age":13}`
var stu = &Student{}
err = json.Unmarshal([]byte(s2), stu)
if err != nil {
panic(err)
}
fmt.Printf("Unmarshal: Name: %s, Age: %d\n", stu.Name, stu.Age) //Unmarshal: Name: Judy, Age: 13
}