Wednesday 15 May 2019

Go: Convert type/struct to json string


Step 1: Create a type Employee
type Employee struct {
         FirstName string
         LastName  string
         ID        int
}

Step 2: Create an object of type Employee
emp := Employee{FirstName: "Krishna", LastName: "Gurram", ID: 123}

Step 3: Call json.Marshal function to convert given object to byte array
empBytes, err := json.Marshal(emp)

Step 4: Convert the bytes to json string.
jsonStr := string(empBytes)

Find the below working application.

App.go
package main

import (
 "encoding/json"
 "fmt"
)

//Employee represent an employee object
type Employee struct {
 FirstName string
 LastName  string
 ID        int
}

func main() {

 //Step 1: Create an object of type Employee
 emp := Employee{FirstName: "Krishna", LastName: "Ram", ID: 123}

 //Step 2: Call json.Marshal function to convert given object to byte array
 empBytes, err := json.Marshal(emp)

 if err != nil {
  fmt.Println("Can't marshal emp")
  return
 }

 jsonStr := string(empBytes)

 fmt.Println(jsonStr)

}

Output
{"FirstName":"Krishna","LastName":"Ram","ID":123}



Previous                                                 Next                                                 Home

No comments:

Post a Comment