/
json_unmarshal.go
60 lines (51 loc) · 1.23 KB
/
json_unmarshal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"fmt"
"reflect"
"strconv"
"strings"
)
type Person struct {
Name string
Age int
IsStudent bool
}
func main() {
jsonStr := `{
"name": "John Doe",
"age": 30,
"isStudent": false
}`
person := Person{}
parseJSONToStruct(jsonStr, &person)
fmt.Printf("%+v\n", person)
}
func parseJSONToStruct(jsonStr string, v interface{}) {
jsonLines := strings.Split(jsonStr, "\n")
rv := reflect.ValueOf(v).Elem()
for _, line := range jsonLines {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "{") || strings.HasPrefix(line, "}") {
continue
}
parts := strings.SplitN(line, ":", 2)
key := strings.TrimSpace(strings.Trim(parts[0], `"`))
value := strings.TrimSpace(strings.Trim(parts[1], ","))
// Find the corresponding field in the struct
field := rv.FieldByNameFunc(func(fieldName string) bool {
return strings.EqualFold(fieldName, key)
})
if field.IsValid() {
switch field.Kind() {
case reflect.String:
field.SetString(strings.Trim(value, `"`))
case reflect.Int:
intValue, _ := strconv.Atoi(value)
field.SetInt(int64(intValue))
case reflect.Bool:
boolValue := strings.ToLower(value) == "true"
field.SetBool(boolValue)
}
}
}
}