Custom Search

Sunday, August 21, 2016

Go Golang Lowercase key names with JSON Marshal and UnMarshal

package main

/* */
import (

/*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"}}*/

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

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

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


No comments:

Post a Comment