-
Notifications
You must be signed in to change notification settings - Fork 9
/
JSONstreams.go
80 lines (68 loc) · 1.37 KB
/
JSONstreams.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"bytes"
"encoding/json"
"fmt"
"math/rand"
)
type Data struct {
Key string `json:"key"`
Val int `json:"value"`
}
var DataRecords []Data
func random(min, max int) int {
return rand.Intn(max-min) + min
}
var MIN = 0
var MAX = 26
func getString(l int64) string {
startChar := "A"
temp := ""
var i int64 = 1
for {
myRand := random(MIN, MAX)
newChar := string(startChar[0] + byte(myRand))
temp = temp + newChar
if i == l {
break
}
i++
}
return temp
}
// DeSerialize decodes a serialized slice with JSON records
func DeSerialize(e *json.Decoder, slice interface{}) error {
return e.Decode(slice)
}
// Serialize serializes a slice with JSON records
func Serialize(e *json.Encoder, slice interface{}) error {
return e.Encode(slice)
}
func main() {
// Create sample data
var i int
var t Data
for i = 0; i < 2; i++ {
t = Data{
Key: getString(5),
Val: random(1, 100),
}
DataRecords = append(DataRecords, t)
}
// bytes.Buffer is both an io.Reader and io.Writer
buf := new(bytes.Buffer)
encoder := json.NewEncoder(buf)
err := Serialize(encoder, DataRecords)
if err != nil {
fmt.Println(err)
return
}
fmt.Print("After Serialize:", buf)
decoder := json.NewDecoder(buf)
var temp []Data
err = DeSerialize(decoder, &temp)
fmt.Println("After DeSerialize:")
for index, value := range temp {
fmt.Println(index, value)
}
}