Wednesday 15 May 2019

Go: customize json using field tags


You can customize json data using field tags.

For example, I added field tags to Employee struct like below.

type Employee struct {
         FirstName string `json:"fName"`
         LastName  string `json:"lName"`
         ID        int    `json:"id"`
}

Whenever you marshall Employee type to a jsin string, it uses field tags instead of Actual field names.

Example
emp := Employee{FirstName: "Krishna", LastName: "Gurram", ID: 123}

If you marshall ‘emp’, you will get below json string.
{"fName":"Krishna","lName":"Gurram","id":123}

App.go
package main

import (
 "encoding/json"
 "fmt"
)

//Employee represent an employee object
type Employee struct {
 FirstName string `json:"fName"`
 LastName  string `json:"lName"`
 ID        int    `json:"id"`
}

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
 }

 jsonStr := string(empBytes)

 fmt.Println(jsonStr)

}

Output
{"fName":"Krishna","lName":"Gurram","id":123}



Previous                                                 Next                                                 Home

No comments:

Post a Comment