Json to Struct and Struct to Json in Golang
In this post we will see the conversion between struct and json#
If you are building any api or anything there might be scenario where you had to convert json data into predefined struct or reverse of that, so we will see how you can do that
Golang’s default library have lots of things done already for our simplicity. Its default library is huge almost for every scenario you will get the default package. go support lots of conversion mechanism like xml json. these conversion comes under encoding
package.
- json.Marshal() this will convert struct to json
- json.Unmarshal() this will convert json to struct
for converting struct into json we have to user json tag at struct level to specify the json key name otherwise it will take the name of struct field.
for example:
type User struct {
Username string `json:"username"`
Firstname string `json:"first_name"`
Lastname string `json:"last_name"`
Email string `json:"email"`
}
json tag is very important for Marshaling and Unmarshaling both
fields of struct must be exported means it should be first letter uppercase otherwise Marshal function wont be able to read those fields.
Please see the whole code to understand how we can use. it is very easy
package main
import (
"encoding/json"
"fmt"
)
func main() {
type User struct {
Username string `json:"username"`
Firstname string `json:"first_name"`
Lastname string `json:"last_name"`
Email string `json:"email"`
}
user := &User{
Username: "devjohn",
Firstname: "John",
Lastname: "Cena",
Email: "abc@gmail.com",
}
jsonData, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(jsonData))
userArr := []User{
*user,
*user,
}
jsonArrData, err := json.Marshal(userArr)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(jsonArrData))
// decoding json into struct
jsonString := "[{\"username\":\"devjohn\",\"first_name\":\"John\",\"last_name\":\"Cena\",\"email\":\"abc@gmail.com\"}]"
var userStruct []User
err = json.Unmarshal([]byte(jsonString), &userStruct)
if err != nil {
panic(err)
}
fmt.Println(userStruct)
}
For xml conversion there is package encoding/xml
. i will write a post on that also.