Last active
September 28, 2018 09:29
-
-
Save khajer/a8713f0ada50487c5a29c627320da818 to your computer and use it in GitHub Desktop.
json string 2 struct golang
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
| /* | |
| final output | |
| type Simple struct { | |
| Status string `json:"status"` | |
| Message string `json:"message"` | |
| Test float64 `json:"test"` | |
| Test1 float64 `json:"test1"` | |
| Ar []string `json:"ar"` | |
| type Result struct { | |
| Eligible float64 `json:"eligible"` | |
| Whitelist string `json:"whitelist"` | |
| type Home struct { | |
| Lname string `json:"lname"` | |
| Agae string `json:"agae"` | |
| Name string `json:"name"` | |
| } `json:"home"` | |
| } `json:"result"` | |
| } | |
| */ | |
| package main | |
| import ( | |
| "fmt" | |
| "encoding/json" | |
| "strings" | |
| "reflect" | |
| ) | |
| func upperCaseText(str string) string{ | |
| return strings.ToUpper(str[0:1])+str[1:] | |
| } | |
| func parseData(structName string, dat map[string]interface{}, tabLevel string) string{ | |
| txt := "" | |
| structRootName := "" | |
| if len(tabLevel) > 0 { | |
| structRootName = "`json:\""+structName+"\"`" | |
| } | |
| txt = tabLevel+"type "+upperCaseText(structName)+" struct {\n" | |
| for k, v := range dat{ | |
| typeReflect := reflect.ValueOf(v) | |
| t := typeReflect.Kind().String() | |
| if t == "map" { | |
| txt += parseData( k, v.(map[string]interface{}), tabLevel+"\t") | |
| }else{ | |
| if t == "slice" { | |
| d := v.([]interface{})[0] | |
| b := reflect.ValueOf(d).Kind().String() | |
| txt += "\t"+upperCaseText(k)+"\t\t[]"+b+" `json:\""+k+"\"`\n" | |
| }else if t == "invalid"{ | |
| t = "interface" | |
| }else{ | |
| txt += tabLevel+"\t"+upperCaseText(k)+"\t\t"+t+" `json:\""+k+"\"`\n" | |
| } | |
| } | |
| } | |
| txt+=tabLevel+"} "+structRootName+"\n" | |
| return txt | |
| } | |
| func main() { | |
| fmt.Println("########## [start process] ##########") | |
| dat := `{ | |
| "status": "OK", | |
| "message": "SUCCESS", | |
| "test": 12, | |
| "test1": 23.00, | |
| "ar":["test", "est2"], | |
| "result": { | |
| "eligible": 1, | |
| "merchant": null, | |
| "whitelist": "", | |
| "home":{ | |
| "name":"xxx", | |
| "lname":"xxx", | |
| "agae":"test" | |
| } | |
| } | |
| }` | |
| var datJson map[string]interface{} | |
| json.Unmarshal([]byte(dat), &datJson) | |
| txt := parseData("simple", datJson, "") | |
| println(txt) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment