Custom Search

Sunday, August 21, 2016

Go Golang decode unmarshal json string to struct

package main

import (
"encoding/json"
"fmt"
"reflect"
)

type Person struct {
Name    string
Age     int
Details interface{}
}



func main() {

str := `{"name": "sam",
             "age": 30,
             "details": {"salary":10000}
            }`

/*This means the key of map named data is a string but the value can be anything*/
/*An interface{} type is a type that could be any value. It’s like Object in Java.*/
var data Person

fmt.Println("==type of str==", reflect.TypeOf(str))
fmt.Println("==str==", str)

/*json.Unmarshal is used when the input is []byte*/
/*stores the decoded result in map named data*/
fmt.Println("==[]byte(str)==", []byte(str))
err := json.Unmarshal([]byte(str), &data)

if err != nil {
panic(err)
}

fmt.Printf("==data==%#v \n\n", data)
fmt.Println("==name== ", data.Name)

/*Type assertions, check type of data["details"]
 https://tour.golang.org/methods/15*/
details, ok := data.Details.(map[string]interface{})
if ok {
fmt.Println("==salary== ", details["salary"])
}
}

No comments:

Post a Comment