Golang encoding/json: Difference between revisions
From wikinotes
Line 54: | Line 54: | ||
== Struct to Json-Object == | == Struct to Json-Object == | ||
<blockquote> | <blockquote> | ||
Only '''exported fields''' will be serialized by default. | |||
<syntaxhighlight lang="go"> | |||
type User struct { | |||
id int | |||
Name string | |||
} | |||
user := User{id: 1, Name: "will"} | |||
bytes, _ := json.Marshal(user) | |||
fmt.Println(string(bytes)) // '{"Name": "will"}' | |||
</syntaxhighlight> | |||
</blockquote><!-- Struct to Json-Object --> | </blockquote><!-- Struct to Json-Object --> | ||
</blockquote><!-- Serializing --> | </blockquote><!-- Serializing --> |
Revision as of 17:39, 25 June 2022
Conveniently, the builtin types are ready for json serialization/deserialization without any additional work.
Deserializing
Builtins
// 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
Builtins
// string, int bytes, _ := json.Marshal("vaderd") fmt.Println(string(bytes)) // '"vaderd"' // array, slice names := []string{"maize", "sprout"} bytes, _ := json.Marshal(names) fmt.Println(string(bytes)) // '["maize", "sprout"]'Struct to Json-Object
Only exported fields will be serialized by default.
type User struct { id int Name string } user := User{id: 1, Name: "will"} bytes, _ := json.Marshal(user) fmt.Println(string(bytes)) // '{"Name": "will"}'