Golang encoding: Difference between revisions

From wikinotes
No edit summary
No edit summary
 
(11 intermediate revisions by the same user not shown)
Line 1: Line 1:
Golang's <code>encoding</code> module defines the interfaces for data serialization.
Serializing and Deserializing objects.


= Basics =
= Interface =
<blockquote>
<blockquote>
Each method of encoding implements at least one of these interfaces
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">
<syntaxhighlight lang="go">
type BinaryMarshaler   interface { MarshalBinary() (data []byte, err error) }
type User struct {
type BinaryUnmarshaler interface { UnmarshalBinary(data []byte) error }
    Id:   int    `json:"id" xml:"id"`
type TextMarshaler    interface { MarshallText(text []byte) error }
    Name: string `json:"name" xml:"name"`
type TextUnmarshaler  interface { UnmarshalText(text []byte) error }
}
user := User{1, "will"}
bytes, err := json.Marshall(&user)
</syntaxhighlight>
</syntaxhighlight>


Rather than a top-down approach, you define types that can be serialized/deserialized.<br>
deserialize
When deserializing, you cat the type, and deserialization is automatic.
<syntaxhighlight lang="go">
<syntaxhighlight lang="go">
 
var mapping map[string]int
var serialized := []byte(`{"a": 1}`)
json.Unmarshall(serialized, &mapping)
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Basics -->
</blockquote><!-- Interface -->


= Libraries =
= Libraries =
Line 23: Line 30:
<blockquote>
<blockquote>
{|
{|
|-
| [[golang encoding/json]]
|-
|-
| [[golang encoding/xml]]
| [[golang encoding/xml]]
|-
| [[golang encoding/csv]]
|-
|-
|}
|}
</blockquote><!-- Builtin -->
</blockquote><!-- Builtin -->
</blockquote><!-- Libraries -->
</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