forked from cosmos/cosmos-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.go
58 lines (46 loc) · 1.13 KB
/
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
package collections
import (
"encoding/json"
"fmt"
"cosmossdk.io/collections/codec"
)
func NewJSONValueCodec[T any]() codec.ValueCodec[T] {
return jsonValue[T]{
typeName: fmt.Sprintf("%T", new(T)),
}
}
type jsonValue[T any] struct {
typeName string
}
// Decode implements codec.ValueCodec.
func (jsonValue[T]) Decode(b []byte) (T, error) {
var t T
if err := json.Unmarshal(b, &t); err != nil {
return t, err
}
return t, nil
}
// DecodeJSON implements codec.ValueCodec.
func (jsonValue[T]) DecodeJSON(b []byte) (T, error) {
var t T
if err := json.Unmarshal(b, &t); err != nil {
return t, err
}
return t, nil
}
// Encode implements codec.ValueCodec.
func (jsonValue[T]) Encode(value T) ([]byte, error) {
return json.Marshal(value)
}
// EncodeJSON implements codec.ValueCodec.
func (jsonValue[T]) EncodeJSON(value T) ([]byte, error) {
return json.Marshal(value)
}
// Stringify implements codec.ValueCodec.
func (jsonValue[T]) Stringify(value T) string {
return fmt.Sprintf("%v", value)
}
// ValueType implements codec.ValueCodec.
func (jv jsonValue[T]) ValueType() string {
return fmt.Sprintf("json(%s)", jv.typeName)
}