-
Notifications
You must be signed in to change notification settings - Fork 5
/
struct_json.go
63 lines (53 loc) · 1.02 KB
/
struct_json.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
61
62
63
package rod_helper
import (
"encoding/json"
"io"
"os"
"path/filepath"
)
// ToFile 注意传入的不是指针
func ToFile(srcJsonFileFPath string, input interface{}) error {
jsonBytes, err := json.Marshal(input)
if err != nil {
return err
}
file, err := os.Create(filepath.FromSlash(srcJsonFileFPath))
if err != nil {
return err
}
defer func() {
_ = file.Close()
}()
_, err = file.Write(jsonBytes)
if err != nil {
return err
}
return nil
}
// ToStruct 传入的必须是指针
func ToStruct(desJsonFileFPath string, output interface{}) error {
file, err := os.Open(filepath.FromSlash(desJsonFileFPath))
if err != nil {
return err
}
defer func() {
_ = file.Close()
}()
bytes, err := io.ReadAll(file)
if err != nil {
return err
}
err = BytesToStruct(bytes, output)
if err != nil {
return err
}
return nil
}
// BytesToStruct 传入的必须是指针
func BytesToStruct(bytes []byte, output interface{}) error {
err := json.Unmarshal(bytes, output)
if err != nil {
return err
}
return nil
}