Entities
Create new folder named entities. In entities folder, create new entities as below:
Category Entity
In entities folder, create new file named category.go as below:
package entities
type Category struct {
Id string `json:"id"`
Name string `json:"name"`
}
Comment Entity
In entities folder, create new file named comment.go as below:
package entities
type Comment struct {
Title string `json:"title"`
Content string `json:"content"`
}
Product Entity
In entities folder, create new file named product.go as below:
package entities
type Product struct {
Id string `json:"id"`
Name string `json:"name"`
Price float32 `json:"price"`
Quantity int `json:"quantity"`
Status bool `json:"status"`
Category Category `json:"category"`
Comments []Comment `json:"comments"`
}
Application
Create new folder named src. In src folder, create new file named main.go as below:
package main
import (
"encoding/json"
"entities"
"fmt"
)
func main() {
var str string = `{
"id":"p01",
"name":"name 1",
"price":4.5,
"quantity":8,
"status":true,
"category":{
"id":"c1",
"name":"Category 1"
},
"comments":[
{"title":"title 1","content":"content 1"},
{"title":"title 2","content":"content 2"},
{"title":"title 3","content":"content 3"}
]
}`
var product entities.Product
json.Unmarshal([]byte(str), &product)
fmt.Println("Product Info")
fmt.Printf("Id: %s\nName: %s\nPrice: %0.2f\nQuantity: %d\nStatus: %t", product.Id, product.Name, product.Price, product.Quantity, product.Status)
fmt.Println("Category Info")
fmt.Println("\tCategory Id: ", product.Category.Id)
fmt.Println("\tCategory Name: ", product.Category.Name)
fmt.Println("Comment List")
for _, comment := range product.Comments {
fmt.Println("\t", comment.Title)
fmt.Println("\t", comment.Content)
fmt.Println("\t-----------------------")
}
}
Output
Open Terminal windows in Visual Studio Code and run command line: go run main.go
Product Info
Id: p01
Name: name 1
Price: 4.50
Quantity: 8
Status: trueCategory Info
Category Id: c1
Category Name: Category 1
Comment List
title 1
content 1
-----------------------
title 2
content 2
-----------------------
title 3
content 3
-----------------------