Golang encoding: Difference between revisions

From wikinotes
No edit summary
 
(7 intermediate revisions by the same user not shown)
Line 1: Line 1:
Serializing and Deserializing objects.
= Interface =
<blockquote>
The encoding libraries mostly share a common interface, for serialization/deserialization.<br>
Optional encoding-specific information is stored in struct-tags.<br>
Some encodings (ex. xml) have additional encoding-specific semantics.
serialize
<syntaxhighlight lang="go">
type User struct {
    Id:  int    `json:"id" xml:"id"`
    Name: string `json:"name" xml:"name"`
}
user := User{1, "will"}
bytes, err := json.Marshall(&user)
</syntaxhighlight>
deserialize
<syntaxhighlight lang="go">
var mapping map[string]int
var serialized := []byte(`{"a": 1}`)
json.Unmarshall(serialized, &mapping)
</syntaxhighlight>
</blockquote><!-- Interface -->
= Libraries =
<blockquote>
== Builtin ==
== Builtin ==
<blockquote>
<blockquote>
Line 11: Line 39:
|}
|}
</blockquote><!-- Builtin -->
</blockquote><!-- Builtin -->
</blockquote><!-- Libraries -->

Latest revision as of 13:50, 26 June 2022

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