Wednesday 15 May 2019

Go: json: Unmarshal byte array to struct


Step 1: Define byte array
byteArray := []byte{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}

Step 2: Define an Employee variable and unmarshal the byte array to employee variable.
var emp Employee
err := json.Unmarshal(byteArray, &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 (emp *Employee) aboutMe() {
 fmt.Println("FirstName : ", emp.FirstName)
 fmt.Println("LastName : ", emp.LastName)
 fmt.Println("ID : ", emp.ID)
}

func main() {

 //Step 1: Define byte array
 byteArray := []byte{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}

 //Step 2: Define an Employee variable and unmarshal the byte array to employee varaible
 var emp Employee
 err := json.Unmarshal(byteArray, &emp)

 if err != nil {
  fmt.Println("Can;t unmarshal the byte array")
  return
 }

 emp.aboutMe()

}

Output
FirstName :  Krishna
LastName :  Gurram
ID :  123



Previous                                                 Next                                                 Home

No comments:

Post a Comment