Wednesday 15 May 2019

Go : Convert type/struct to json byte array


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)

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: "Gurram", 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
 }

 fmt.Println(empBytes)

}

Output
[123 34 70 105 114 115 116 78 97 109 101 34 58 34 75 114 105 115 104 110 97 34 44 34 76 97 115 116 78 97 109 101 34 58 34 71 117 114 114 97 109 34 44 34 73 68 34 58 49 50 51 125]


Previous                                                 Next                                                 Home

No comments:

Post a Comment