Custom Search

Sunday, August 21, 2016

Go Golang Lowercase key names with JSON Marshal and UnMarshal

package main

/* https://golang.org/pkg/fmt/ */
import (
"encoding/json"
"fmt"
)



/*A struct is a type which contains named fields.
Define new type named 'Person'*/
type Person struct {
Name    string   `json:"name"`
Age     int      `json:"age"`
Hobbies []string `json:"hobbies"`
}

func main() {

/*initialize a struct.
 Create an instance of type 'Person'*/
p1 := Person{"Sam", 20, []string{"cricket", "football"}}
/*p1 := &Person{name: "Sam", age: 20, hobbies: []string{"cricket", "football"}}*/

/*ENCODE*/
/*p1_json_ind, _ := json.MarshalIndent(p1, "", "  ")*/
p1_json, _ := json.Marshal(p1)
fmt.Println("==p1_json==", string(p1_json))

/*DECODE*/
var p2 Person
decode_error := json.Unmarshal(p1_json, &p2)
fmt.Printf("==decode_error==%v \n", decode_error)

fmt.Printf("==p2==%#v \n", p2)

}

1 comment: