Golang encoding/json: Difference between revisions

From wikinotes
No edit summary
Line 6: Line 6:
<blockquote>
<blockquote>
<syntaxhighlight lang="go">
<syntaxhighlight lang="go">
// string, int
var name string
var name string
json.Unmarshal([]byte(`"vaderd"`), &name)
json.Unmarshal([]byte(`"vaderd"`), &name)
fmt.Println(name)
fmt.Println(name)
// array, slice
var items [2]string
json.Unmarshal([]byte(`["abc", "def"]`), &items)
fmt.Println(items)  // [abc def]
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Primitives -->
</blockquote><!-- Primitives -->
== Json-Array to Slice ==
<blockquote>
<syntaxhighlight lang="go">
func main() {
    var items []string
    json.Unmarshal([]byte(`["123", "456"]`), &items)
    fmt.Println(items)
}
</syntaxhighlight>
</blockquote><!-- Json-Array to Slice -->


== Json-Object to Struct ==
== Json-Object to Struct ==

Revision as of 14:45, 25 June 2022

Conveniently, the builtin types are ready for json serialization/deserialization without any additional work.

Deserializing

Primitives

// string, int
var name string
json.Unmarshal([]byte(`"vaderd"`), &name)
fmt.Println(name)

// array, slice
var items [2]string
json.Unmarshal([]byte(`["abc", "def"]`), &items)
fmt.Println(items)  // [abc def]

Json-Object to Struct

type User struct {
    id   int
    Name string
}

func main() {
    var user User
    data := []byte(`{"id": 123, "Name": "vaderd"}`)
    json.Unmarshal(data, &user)
    fmt.Println(user.Name)
}

Serializing

Primitives

// string
bytes, _ := json.Marshal("vaderd")
fmt.Println(string(bytes))

// integer
bytes, _ := json.Marshall(123)
fmt.Println(string(bytes))

Slice to Json-Array

Struct to Json-Object