OSDN Git Service

Osssync (#580)
[bytom/vapor.git] / toolbar / osssync / util / json.go
1 package util
2
3 import (
4         "encoding/json"
5         "io/ioutil"
6 )
7
8 // NewFileUtil creates new file util
9 func NewFileUtil(localDir string) *FileUtil {
10         return &FileUtil{localDir}
11 }
12
13 // SaveBlockFile saves block file
14 func (f *FileUtil) SaveBlockFile(filename string, data interface{}) (bool, error) {
15         filename = f.LocalDir + filename + ".json"
16         saveData, err := json.Marshal(data)
17         if err != nil {
18                 return false, err
19         }
20
21         err = ioutil.WriteFile(filename, saveData, 0644)
22         if err != nil {
23                 return false, err
24         }
25
26         return true, nil
27 }
28
29 // GetJson read json file
30 func (f *FileUtil) GetJson(filename string) (json.RawMessage, error) {
31         filename = f.LocalDir + filename + ".json"
32         return ioutil.ReadFile(filename)
33 }
34
35 // Json2Struct transform json to struct
36 func Json2Struct(data json.RawMessage, resp interface{}) error {
37         return json.Unmarshal(data, &resp)
38 }
39
40 // Struct2Json transform struct to json
41 func Struct2Json(theStruct interface{}) (json.RawMessage, error) {
42         return json.Marshal(theStruct)
43 }