/
feature.json.go
95 lines (80 loc) · 2.05 KB
/
feature.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package geom
import (
jsoniter "github.com/json-iterator/go"
"github.com/mojo-lang/core/go/pkg/mojo/core"
"sort"
"unsafe"
)
func init() {
core.RegisterJSONTypeDecoder("geom.Feature", &FeatureCodec{})
core.RegisterJSONTypeEncoder("geom.Feature", &FeatureCodec{})
}
type FeatureCodec struct {
}
func (codec *FeatureCodec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
a := iter.ReadAny()
if a.ValueType() == jsoniter.ObjectValue {
t := a.Get("type").ToString()
if t != "Feature" {
return
}
feature := (*Feature)(ptr)
feature.Id, _ = core.NewIdCodec().DecodeAny(a.Get("id"))
g := a.Get("geometry")
if g.ValueType() == jsoniter.ObjectValue {
feature.Geometry = &Geometry{}
g.ToVal(feature.Geometry)
} else {
feature.Geometry = nil
}
p := a.Get("properties")
feature.Properties = make(map[string]*core.Value)
for _, key := range p.Keys() {
value, err := core.NewValueCodec().DecodeAny(p.Get(key))
if err != nil {
iter.ReportError("Decode Feature Properties", err.Error())
} else {
feature.Properties[key] = value
}
}
}
}
func (codec *FeatureCodec) IsEmpty(ptr unsafe.Pointer) bool {
return ((*Feature)(ptr)).Geometry == nil
}
func (codec *FeatureCodec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
feature := (*Feature)(ptr)
stream.WriteObjectStart()
stream.WriteObjectField("type")
stream.WriteString("Feature")
if feature.Id != nil {
stream.WriteMore()
stream.WriteObjectField("id")
stream.WriteVal(feature.Id)
}
stream.WriteMore()
stream.WriteObjectField("geometry")
stream.WriteVal(feature.Geometry)
stream.WriteMore()
stream.WriteObjectField("properties")
properties := feature.Properties
if len(properties) == 0 {
stream.WriteVal(nil)
} else {
stream.WriteObjectStart()
var keys []string
for key := range properties {
keys = append(keys, key)
}
sort.Strings(keys)
for i, key := range keys {
if i > 0 {
stream.WriteMore()
}
stream.WriteObjectField(key)
stream.WriteVal(properties[key])
}
stream.WriteObjectEnd()
}
stream.WriteObjectEnd()
}