Marshal in Golang

Create new folder named entities. In entities folder, create new entities as below:

In entities folder, create new file named category.go as below:

package entities

type Category struct {
	Id   string `json:"id"`
	Name string `json:"name"`
}

In entities folder, create new file named comment.go as below:

package entities

type Comment struct {
	Title   string `json:"title"`
	Content string `json:"content"`
}




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"`
}

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() {

	product := entities.Product{
		Id:       "p01",
		Name:     "name 1",
		Price:    4.5,
		Quantity: 8,
		Status:   true,
		Category: entities.Category{
			Id:   "c1",
			Name: "Category 1",
		},
		Comments: []entities.Comment{
			entities.Comment{Title: "title 1", Content: "content 1"},
			entities.Comment{Title: "title 2", Content: "content 2"},
			entities.Comment{Title: "title 3", Content: "content 3"},
		},
	}
	result, err := json.Marshal(product)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(string(result))
	}

}




Open Terminal windows in Visual Studio Code and run command line: go run main.go

{"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"}]}