Created
October 3, 2018 02:05
-
-
Save ariesmcrae/2e099c305a22967b1d8d2b45ca27c4e8 to your computer and use it in GitHub Desktop.
golang: Unmarshall json to struct
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// play.golang.org/p/-fTKnXVctQ0 | |
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
) | |
type Employee struct { | |
FirstName string `json:"first_name"` | |
LastName string `json:"last_name"` | |
} | |
/* Unmarshall json to struct */ | |
func main() { | |
employeeJsonStr := `{ | |
"first_name":"John", | |
"last_name":"Smith" | |
}` | |
employee := unmarshall(employeeJsonStr) | |
fmt.Println(employee.FirstName) // John | |
fmt.Println(employee.LastName) // Smith | |
} | |
func unmarshall(employeeJsonStr string) Employee { | |
employee := &Employee{} | |
json.Unmarshal([]byte(employeeJsonStr), employee) | |
return *employee | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment