Golang encoding

From wikinotes
Revision as of 13:50, 26 June 2022 by Will (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Serializing and Deserializing objects.

Interface

The encoding libraries mostly share a common interface, for serialization/deserialization.
Optional encoding-specific information is stored in struct-tags.
Some encodings (ex. xml) have additional encoding-specific semantics.

serialize

type User struct {
    Id:   int    `json:"id" xml:"id"`
    Name: string `json:"name" xml:"name"`
}
user := User{1, "will"}
bytes, err := json.Marshall(&user)

deserialize

var mapping map[string]int
var serialized := []byte(`{"a": 1}`)
json.Unmarshall(serialized, &mapping)

Libraries

Builtin

golang encoding/json
golang encoding/xml
golang encoding/csv